我有两个对象数组:
Array1:
[[0] => stdClass, [1] => stdClass, [2] => stdClass]
Array2
[[0] => stdClass, [1] => stdClass
我想得到两个数组(Array1-Array2(之间的差异。
它是否存在一种更好的方法,而不是迭代两个数组并检查对象的属性?非常感谢
您可以使用经典的array_diff
,但需要处理字符串,而不是要比较的数组中的对象。
因此,您可以将这些数组映射到JSON字符串,然后它们将恢复此转换
<?php
$a = [(object)array('a' => 'b'), (object)array('c' => 'd'), (object)array('e' => 'f')];
$b = [(object)array('a' => 'b'), (object)array('g' => 'h')];
var_dump(array_map('json_decode', array_diff(array_map('json_encode', $a), array_map('json_encode', $b))));
此代码将打印:
array(2) {
[1]=>
object(stdClass)#6 (1) {
["c"]=>
string(1) "d"
}
[2]=>
object(stdClass)#7 (1) {
["e"]=>
string(1) "f"
}
}
因此,这些元素存在于$a
中,而不存在于$b
中。
链接下也考虑了类似的问题:
array_diff((与多维数组