php PHP获取两个对象数组的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6472183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:29:15  来源:igfitidea点击:

PHP get difference of two arrays of objects

phparrays

提问by roflwaffle

I know there is array_diffand array_udifffor comparing the difference between two arrays, but how would I do it with two arrays of objects?

我知道存在array_diff并且array_udiff用于比较两个数组之间的差异,但是我将如何处理两个对象数组?

array(4) {
    [0]=>
        object(stdClass)#32 (9) {
            ["id"]=>
            string(3) "205"
            ["day_id"]=>
            string(2) "12"
        }
}

My arrays are like this one, I am interested to see the difference of two arrays based on IDs.

我的数组是这样的,我有兴趣查看基于 ID 的两个数组的差异。

回答by Jordan Running

This is exactly what array_udiffis for. Write a function that compares two objects the way you would like, then tell array_udiffto use that function. Something like this:

这正是array_udiff它的目的。编写一个函数,以您想要的方式比较两个对象,然后告诉array_udiff使用该函数。像这样的东西:

function compare_objects($obj_a, $obj_b) {
  return $obj_a->id - $obj_b->id;
}

$diff = array_udiff($first_array, $second_array, 'compare_objects');

Or, if you're using PHP >= 5.3 you can just use an anonymous functioninstead of declaring a function:

或者,如果您使用 PHP >= 5.3,您可以只使用匿名函数而不是声明函数:

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return $obj_a->id - $obj_b->id;
  }
);

回答by megastruktur

And here is another option if you wanna compare string properties (e.g. name):

如果您想比较字符串属性(例如名称),这是另一种选择:

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return strcmp($obj_a->name, $obj_b->name);
  }
);

回答by patricksayshi

Here's another option, if you want to run the diff according to object instances. You would use this as your callback to array_udiff:

这是另一种选择,如果您想根据对象实例运行差异。您将使用它作为您的回调array_udiff

function compare_objects($a, $b) {
    return strcmp(spl_object_hash($a), spl_object_hash($b));
}

You'd only want to use that if you're certain that the arrays both contain only objects - here's my personal use case.

如果您确定数组都只包含对象,那么您只想使用它 -这是我的个人用例