问题描述
我知道有array_diff
和array_udiff
用于比较两个数组之间的差异,但是我将如何使用两个对象数组进行比较?
I know there is array_diff
and array_udiff
for comparing the difference between two arrays, but how would I do it with two arrays of objects?
array(4) {
[0]=>
object(stdClass)#32 (9) {
["id"]=>
string(3) "205"
["day_id"]=>
string(2) "12"
}
}
我的数组就像这样,我很想看看基于ID的两个数组的区别.
My arrays are like this one, I am interested to see the difference of two arrays based on IDs.
推荐答案
这正是 array_udiff
的用途.编写一个函数,以您希望的方式比较两个对象,然后告诉array_udiff
使用该函数.像这样:
This is exactly what array_udiff
is for. Write a function that compares two objects the way you would like, then tell array_udiff
to use that function. Something like this:
function compare_objects($obj_a, $obj_b) {
return $obj_a->id - $obj_b->id;
}
$diff = array_udiff($first_array, $second_array, 'compare_objects');
或者,如果您使用的是PHP> = 5.3,则可以使用匿名函数而不是声明函数:
Or, if you're using PHP >= 5.3 you can just use an anonymous function instead of declaring a function:
$diff = array_udiff($first_array, $second_array,
function ($obj_a, $obj_b) {
return $obj_a->id - $obj_b->id;
}
);
这篇关于PHP获得两个对象数组的差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!