4
3

More than 5 years have passed since last update.

【PHP】連想配列向けのarray_diff

Posted at

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
)
*/
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3