数组差异返回编辑的值

时间:2017-05-18 01:31:12

标签: php

以下代码检查第一个数组(parameter1)和第二个数组(parameter2),并返回一个数组,告诉哪些元素被修改。

$array_data   = array(
    "studDetails" => array(
        "studDet" => array(
            "studClass" => "V",
        ),
    ),
    "email"       => "kavya@opspl.com",
    "systemNames" => array("EMR"),
);
$array_edited = $array_data;

//EDITING
$array_edited['email'] = "kam";
$array_edited['studDetails']['studDet']['studClass'] = "VV";

echo "<pre>";
print_r(array_diff_assoc2_deep($array_edited, $array_data));


function array_diff_assoc2_deep($array_edited, $array_data)
{
    $difference = array();
    foreach ($array_edited as $row => $value) {
        if (!isset($array_data[$row]) && !empty($value)) {
            $difference['added'][$row] = $value;
        } else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
            $difference[$row] = array_diff_assoc2_deep($array_edited[$row], $array_data[$row]);
        } else if ((string)$value != (string)$array_data[$row]) {
            $difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
        }

    }
    $difference = array_filter($difference);
    return $difference;
}

输出:

Array (
    [studDetails] => Array (
        [studDet] => Array (
            [edited] => Array (
                [studClass] => Array (
                    [old] => V 
                    [new] => VV 
                )
            )
        )
    )
    [edited] => Array (
        [email] => Array (
            [old] => kavya@opspl.com 
            [new] => kam 
        )
    )
)

无论有多少内部数组,我都希望输出在一个编辑的密钥中。

期望的输出:

Array (
    [edited] => Array (
        [email] => Array (
            [old] => kavya@opspl.com 
            [new] => kam 
        )
        [studClass] => Array (
            [old] => V 
            [new] => VV 
        )
    )
)

1 个答案:

答案 0 :(得分:0)

发生这种情况的原因是递归调用:

X>W>Z

使用此行,您可以将每个递归比较结果放入单独的键中。

如果你不这样做但是让结果阵列保持平坦,你就会得到你想要的东西:

$difference[$row] = array_diff_assoc2_deep($array_edited[$row], $array_data[$row]);

三条线已经改变:

function array_diff_assoc2_deep($array_edited, $array_data, $difference = array())
{
    foreach ($array_edited as $row => $value) {
        if (!isset($array_data[$row]) && !empty($value)) {
            $difference['added'][$row] = $value;
        } else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
            $difference = array_diff_assoc2_deep($array_edited[$row], $array_data[$row], $difference);
        } else if ((string)$value != (string)$array_data[$row]) {
            $difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
        }

    }
    $difference = array_filter($difference);
    return $difference;
}

您可以看到输出here