Help us understand the problem. What is going on with this article?

【PHP】連想配列向けのarray_diff

More than 1 year has passed since last update.

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした