我正在尝试用array_udiff()
计算两个对象数组的差异。我的对象结构很复杂,我不能依赖定量属性,因为两个数组中对象的这些属性可能具有相同的值,但它们存储为不同的实例(这是预期行为)。
所以,这是我的问题:有没有办法使用引用检测来检测两个数组中的相同实例?
我试过什么?
我试过这个:
<?php
header('Content-Type: text/plain; charset=utf-8');
$a = new stdClass;
$b = new stdClass;
$c = new stdClass;
$a->a = 123;
$b->b = 456;
$c->c = 789;
$x = [ $a, $c ];
$y = [ $b, $c ];
$func = function(stdClass &$a, stdClass &$b){
$replacer = time();
$buffer = $a;
$a = $replacer;
$result = $a === $b;
$a = $buffer;
return $result;
};
$diff = array_udiff($x, $y, $func);
print_r($diff);
?>
并得到不成功的结果,因为如果我尝试替换$x
元素的值,php 不会从$y
中删除引用。
我有相同的输出:
$func = function(stdClass &$a, stdClass &$b){
return $a === $b;
};
和
$func = function(stdClass &$a, stdClass &$b){
return $a == $b;
};
它是一个空数组。
有什么建议吗?
这是您的问题,来自手册页:
如果第一个参数分别被视为小于、等于或大于第二个参数,则比较函数必须返回小于、等于或大于零的整数。
您返回一个布尔值 ( false
),因为您要将时间戳与对象进行比较。 (int) false
为零,因此每个对象都将被视为相等,因此您的$diff
数组为空。
将回调函数更改为:
$func = function(stdClass $a, stdClass $b)
{//don't pass by reference, it's quite dangerous
$replacer = time();
$buffer = $a;
$a = $replacer;
$result = $a === $b ? 0 : -1;//equal? return zero!
$a = $buffer;
return $result;
};
这将起作用,但现在$diff
显然包含所有对象。而且你的回调有点乱,考虑一下:
$func = function(stdClass $a, stdClass $b)
{//don't pass by reference, it's quite dangerous
return $a === $b ? 0 : -1;//compare objects
//or, if you want to compare to time, still:
return time() === $b ? 0 : -1;
};
那干净得多,更短,不是吗?
注意
您必须返回-1
以防两个对象不相等。在这种情况下,返回1
意味着您正在比较的对象已经大于您与之比较的对象的值。在这种情况下,PHP 将停止查找,并简单地假设该值不存在于您正在比较第一个数组的数组中......好吧,这变得相当复杂。举个例子:
[$a, $c] compare to [$b, $c]:
$a === $b => false: returns 1
PHP assumes $a > $b, so $a > $c is implied, $a is pushed into $diff
$c === $b => false returns 1
PHP assumes $c > $b, and is pushed to $diff, it's never compared to the next elem...
但是,在 false 上返回 -1:
[$a, $c] compare to [$b, $c]:
$a === $b => false: returns -1
PHP assumes $a < $b, so:
$a === $c => false: returns -1
No more elems left, push $a to $diff
$c === $b => false returns -1
PHP assumes $c < $b, moving on:
$c === $c => true returns 0
Match found, $c is NOT pushed to $diff
尽管我已经接受了@Elias Van Ootegem的答案,但它对diff数组中任何可能的对象组合都没有帮助。
要检测引用,您可以使用===
或!==
比较运算符:
使用恒等运算符 (===) 时,对象变量是相同的 当且仅当它们引用同一类的同一实例时。
所以这里是函数,它接受两个数组,但可能会改进以接受更多数组:
function array_exclude_instances(array $source, array $excludes){
foreach($source as $index => $current){
foreach($excludes as $exclude){
if($exclude !== $current)continue 1;
unset($source[$index]);
continue 2;
}
}
return array_values($source);
}
测试:
$a = new stdClass;
$b = new stdClass;
$c = new stdClass;
$a->x = 123;
$b->x = 123;
$c->x = 456;
$x = [$a, $c];
$y = [$c, $b];
$result = array_exclude_instances($x, $y);
结果:
Array
(
[0] => stdClass Object
(
[x] => 123
)
)
在线测试 @ 3v4l。
如果替换会发生什么:
$func = function(stdClass &$a, stdClass &$b)
自:
function func(stdClass &$a, stdClass &$b)
并像这样打电话:
$diff = array_udiff($x, $y, 'func');