2
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

【PHP】連想配列向けのarray_diff

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
)
*/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
2
Help us understand the problem. What are the problem?