元のarray_diffと同じように機能するより優れた関数。
array1を1つ以上の他の配列と比較し、他のどの配列にも再帰的に存在しないarray1の値を返します。
<?php
function md_array_diff(array $array1, array $array2, array $_ = null) {
$diff = [];
$args = array_slice(func_get_args(), 1);
foreach ($array1 as $key => $value) {
foreach ($args as $item) {
if (is_array($item)) {
if (array_key_exists($key, $item)) {
if (is_array($value) && is_array($item[$key])) {
$tmpDiff = md_array_diff($value, $item[$key]);
if (!empty($tmpDiff)) {
foreach ($tmpDiff as $tmpKey => $tmpValue) {
if (isset($item[$key][$tmpKey])) {
if (is_array($value[$tmpKey]) && is_array($item[$key][$tmpKey])) {
$newDiff = array_diff($value[$tmpKey], $item[$key][$tmpKey]);
} else if ($value[$tmpKey] !== $item[$key][$tmpKey]) {
$newDiff = $value[$tmpKey];
}
if (isset($newDiff)) {
$diff[$key][$tmpKey] = $newDiff;
}
} else {
$diff[$key][$tmpKey] = $tmpDiff;
}
}
}
} else if ($value !== $item[$key]) {
$diff[$key] = $value;
}
} else {
$diff[$key] = $value;
}
}
}
}
return $diff;
}
$arr1 = [
"A" => [
"A1" => ['A1-0', 'A1-1', 'A1-2', 'A1-3'],
"A2" => ['A2-0', 'A2-1', 'A2-2', 'A2-3'],
"A3" => ['A3-0', 'A3-1', 'A3-2', 'A3-3']
],
"B" => [
"B1" => ['B1-0', 'B1-1', 'B1-2', 'B1-3'],
"B2" => ['B2-0', 'B2-1', 'B2-2', 'B2-3'],
"B3" => ['B3-0', 'B3-1', 'B3-2', 'B3-3']
],
'C' => 123
];
$arr2 = [
"A" => [
"A1" => ['A1-1', 'A1-2', 'A1-3'],
"A2" => ['A2-0', 'A2-1', 'A2-2', 'A2-3'],
"A3" => ['A3-0', 'A3-1', 'A3-2']
],
"B" => [
"B1" => ['B1-0', 'B1-2', 'B1-3'],
"B2" => ['B2-0', 'B2-1', 'B2-2', 'B2-3'],
"B3" => ['B3-0', 'B3-1', 'B3-3']
]
];
$arr3 = [
"A" => [
"A1" => ['A1-0', 'A1-1', 'A1-2', 'A1-3'],
"A2" => ['A2-0', 'A2-1', 'A2-2', 'A2-3'],
"A3" => ['A3-0', 'A3-1', 'A3-2']
],
"B" => [
"B1" => ['B1-0', 'B1-2', 'B1-3'],
"B2" => ['B2-0', 'B2-1', 'B2-2', 'B2-3'],
"B3" => ['B3-0', 'B3-1', 'B3-3']
]
];
$diff = md_array_diff($arr1, $arr2, $arr3);
?>
Will Output:
array (size=3)
'A' =>
array (size=2)
'A1' =>
array (size=1)
0 => string 'A1-0' (length=4)
'A3' =>
array (size=1)
3 => string 'A3-3' (length=4)
'B' =>
array (size=2)
'B1' =>
array (size=1)
1 => string 'B1-1' (length=4)
'B3' =>
array (size=1)
2 => string 'B3-2' (length=4)
'C' => int 123