我正在寻找一种比较 PHP 中对象数组的简洁方法。我知道我可以只检查大小相等的数组,然后循环遍历一个数组,查找第二个数组中的每个对象,但我认为使用一个或多个数组比较函数会更好。
我测试了几个对象数组,我遇到的主要问题是数组比较函数坚持将元素比较为
strings
,如下所示:
class Foo{
public $pk=NULL;
function __construct($pk){
$this->pk=$pk;
}
function __toString(){
return (string)$this->pk;//even an integer must be cast or array_intersect fails
}
}
for($i=1;$i<7;$i++){
$arr1[]=new Foo($i);
}
for($i=2;$i<5;$i++){
$arr2[]=new Foo($i);
}
$int=array_intersect($arr1,$arr2);
print_r($int);
输出
Array
(
[1] => Foo Object
(
[pk] => 2
)
[2] => Foo Object
(
[pk] => 3
)
[3] => Foo Object
(
[pk] => 4
)
)
如果对象具有
__toString()
方法并且这些 __toString()
方法返回唯一标识符并且从不 ''
。,那就没问题了。
但是如果情况并非如此,会发生什么,比如这样的对象:
class Bar{
public $pk=NULL;
function __construct($pk){
$this->pk=$pk;
}
function __toString(){
return 'I like candy.';//same for all instances
}
function Equals(self $other){
return ($this->pk==$other->pk);
}
}
是否可以通过
array_uintersect($arr1,$arr2,$somecallback)
来强制使用 Foo::Equals()
?据我所知,到 string
的转换发生在调用回调之前。
有什么想法可以解决这个问题吗?
是的,您可以使用
array_uintersect
来实现此目的。
一些示例代码:
class Fos {
public $a = 0;
function __construct($a) {
$this->a = $a;
}
static function compare($a, $b) {
if ($a->a == $b->a) return 0;
if ($a->a > $b->a) return 1;
if ($a->a < $b->a) return -1;
}
}
$fos1 = array();
$fos2 = array();
for ($i = 1; $i < 10; $i++) {
$fos1[] = new Fos($i);
}
for ($i = 8; $i < 18; $i++) {
$fos2[] = new Fos($i);
}
$fosi = array_uintersect($fos1, $fos2, array('Fos','compare'));