array_diff on array of associative arrays in php

↘锁芯ラ 提交于 2020-01-15 15:59:12

问题


I have two arrays of the form

Array1:
[0]=> Array([name] => foo [id] => 12)
[1]=> Array([name] => bar [id] => 34)

Array2:
[0]=>Array([name] => bar [id]=> 34)
[1]=>Array([name] => baz [id]=> 56)

The arrays come from a database and any two pairs can have the same name but ID's are unique. I am trying to compare the arrays by ID likes so:

$one_not_two = array_diff($array1[id], $array2[id]);
but that does not return anything. I also tried
$one_not_two = array_diff($array1[id], $array2[id]);
which returned an error "argument is not an array." Originally I got around it by extracting the IDs into a one-dimensional array and just comparing those but now a new feature requires me to compare the pairs. Any advice?

PS Our servers are running php 5.3 if that makes any difference.


回答1:


Because the arrays are multidimensional you have to extract the ids like this:

$ids1 = array();
foreach($array1 as $elem1)
    $ids1[] = $elem1['id'];

$ids2 = array();
foreach($array2 as $elem2)
    $ids2[] = $elem2['id'];

$one_not_two = array_diff($ids1,$ids2);

For your specific question, check out array_diff() with multidimensional arrays




回答2:


You could use array_udiff to create a custom diff function:

$diff = array_udiff($array1,
                    $array2,
                    function ($a, $b){
                        if($a['id'] == $b['id']){
                            return 0;
                        } else {
                            return ($a['id'] < $b['id'] ? -1 : 1);
                        }
                    }
                );

http://codepad.viper-7.com/2u5EWg




回答3:


If id is unique you can do that:

$one_not_two = array();

foreach ($array1 as $val) {
    $one_not_two[$val['id']] = $val;
}

foreach ($array1 as $val) {
    if (!isset($one_not_two[$val['id']])) {
        $one_not_two[$val['id']] = $val;
}



回答4:


In the end I solved it by changing Array1 to an associative array of name => id




回答5:


Having the same problem as you.

Solved it with: $result = array_diff_assoc($array2, $array1);

Reference: PHP: array_diff_assoc



来源:https://stackoverflow.com/questions/19964353/array-diff-on-array-of-associative-arrays-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!