compare two associative array and display the difference

旧巷老猫 提交于 2020-01-06 14:58:30

问题


I have the following Two array results coming from MySQL query result.

Array One (Orignal-Data):

Array
(
    [w_a] => Array
        (
            [0] => Array
                (
                    [cod] => CRR
                    [pr] => LL
                    [aid] => VM2254
                    [gender] => m
                    [title] => 
                )
        )

    [w_a_ml] => Array
        (
        )

    [w_a_ol] => Array
        (
        )

    [w_a_rl] => Array
        (
            [0] => Array
                (
                    [rol] => 1
                )
        )
)

Array Two (Changed-Data)

Array
(
    [w_a] => Array
        (
            [0] => Array
                (
                    [cod] => CRR
                    [pr] => LL
                    [aid] => VM2254
                    [gender] => f
                    [title] => Mr
                )
        )

    [w_a_ml] => Array
        (
            [0] => Array
                (
                    [wl] => 255
                    [care] => Sahan
                    [heigh] => 
                    [adam] => 
                    [instance] => Look 
                )
        )

    [w_a_ol] => Array
        (
        )

    [w_a_rl] => Array
        (
            [0] => Array
                (
                    [rol] => 1
                )
        )
)

What I wan to achieve from the above two array is to compare and show the result in table format or Inside Form To each Field (Original and New-Change) like below.

    FiledsN     Original    New Change
    title       Empty       Mr
    Wl          Empty       255
    Care        Empty       Sahan
    gender        m         f
    instance    Empty       Look

I've tried making the array a single array using this function:

function array_single($arr) {
    if (!is_array($arr)) {
        return FALSE;
    }
    $res = array();
    foreach ($arr as $keys => $values) {
       if (is_array($values)) {
           $res = array_merge($res, array_single($values));
       } else {
           $res[$keys] = $values;
       }
    }
    return $res;
}

And then comparing using this:

function diff($new,$old) {
    $del=array_diff_assoc($old,$new);
    $add=array_diff_assoc($new,$old);
    return $diff=array("old"=>$del, "new"=>$add);
}

来源:https://stackoverflow.com/questions/18339099/compare-two-associative-array-and-display-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!