比较两个关联数组并显示差异

时间:2013-08-20 15:29:19

标签: php arrays associative-array

我有以下两个来自MySQL查询结果的数组结果。

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
(
    [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
                )
        )
)

我要从上面两个数组中实现的目的是比较并以表格格式显示结果或将内部表格显示到每个字段(原始和新变化),如下所示。

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

我尝试使用此函数将数组设为单个数组:

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;
}

然后用这个比较:

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

0 个答案:

没有答案