我有两个包含数组和对象的多维数组。
$new = [
'a' => 'b',
'c' => (object)[
'd' => [1 => 11, 2 => 12],
'f' => 'Hello',
],
];
$old = [
'a' => 'b',
'c' => (object) [
'd' => [1 => 11, 2 => 22],
'f' => 'Goodbye',
],
];
我正在尝试使用下面的函数查找这两个数组之间的差异,但是当将两个对象一起比较时,结果似乎是错误的。如何更改此功能以获得正确的输出?
function compare($array1, $array2)
{
$result = array();
foreach ($array1 as $key => $value) {
if (is_array($value)) {
if (array_key_exists($key, $array2)) {
$recursiveArrayDiff = compare($value, $array2[$key]);
if (count($recursiveArrayDiff)) {
$result[$key] = $recursiveArrayDiff;
}
continue;
}
else {
$result[$key] = $value;
continue;
}
}
if (is_object($value)) {
if (isset($key, $array2) && is_object($array2[$key])) {
$props = array_keys(get_object_vars($value));
foreach ($props as $prop) {
if (isset($array2[$key]->{$prop})) {
if (is_object($value->{$prop}) && is_object($array2[$key]->{$prop})) {
$temp = compare($value->{$prop}, $array2[$key]->{$prop});
if (count($temp)) {
$result[$key] = array($prop => $temp);
}
continue;
} elseif (is_array($value->{$prop}) && is_array($array2[$key]->{$prop})) {
$temp = compare($value->{$prop}, $array2[$key]->{$prop});
if (count($temp)) {
$result[$key] = array($prop => $temp);
}
continue;
} else {
if ($value->{$prop} != $array2[$key]->{$prop}) {
$result[$key] = array($prop => $value->{$prop});
}
}
} else {
$result[$key] = array($prop => $value->{$prop});
}
}
}
}
if ($value != $array2[$key]) {
$result[$key] = $value;
}
}
return $result;
}
正确和错误的输出如下:
//correct output
Array
(
[c] => stdClass Object
(
[d] => Array
(
[2] => 12
)
[f] => Hello
)
)
//wrong output
Array
(
[c] => stdClass Object
(
[d] => Array
(
[1] => 11
[2] => 12
)
[f] => Hello
)
)