我正在寻找一种比较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
。
任何想法如何解决这个问题?
答案 0 :(得分:7)
是的,您可以使用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'));