array_diffの連想配列対応バージョン
function array_diff_recursive($keys, $array1, ...$arrayn)
{
foreach ($arrayn as $arrayi) {
$array1 = array_udiff($array1, $arrayi, function($a, $b) use ($keys){
foreach ($keys as $key) {
$cmp = $a[$key] <=> $b[$key];
if ($cmp) return $cmp;
}
return $cmp;
});
}
return $array1;
}
$array1
とその他いくつかの$arrayn
を$keys
について比較し、$array1
にのみ存在する要素を返します。
<?php
$a = [
[ 'id' => 123, 'name' => aa, 'removed' => true, 'state' => 2 ],
[ 'id' => 4532, 'name' => bb, 'removed' => false, 'state' => 1 ],
[ 'id' => 772, 'name' => cc, 'removed' => true, 'state' => 0 ],
[ 'id' => 6956, 'name' => dd, 'removed' => true, 'state' => 0 ],
[ 'id' => 832, 'name' => ee, 'removed' => false, 'state' => 1 ],
];
$b = [
[ 'id' => 498, 'name' => ff, 'removed' => true, 'state' => 2 ],
[ 'id' => 4532, 'name' => bb, 'removed' => false, 'state' => 1 ],
[ 'id' => 832, 'name' => ee, 'removed' => false, 'state' => 1 ],
];
$c = [
[ 'id' => 498, 'name' => ff, 'removed' => true, 'state' => 2 ],
[ 'id' => 783, 'name' => gg, 'removed' => false, 'state' => 1 ],
[ 'id' => 6956, 'name' => sd, 'removed' => true, 'state' => 0 ],
];
$d = array_diff_recursive(['id'], $a,$b,$c);
print_r(array_keys($d));
/*
Array
(
[0] => 0
[1] => 2
)
*/
$d = array_diff_recursive(['id','name'], $a,$b,$c);
print_r(array_keys($d));
/*
Array
(
[0] => 0
[1] => 2
[2] => 3
)
*/