比较对象数组

dna*_*irl 5 php arrays object

我正在寻找一种比较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);
Run Code Online (Sandbox Code Playgroud)

输出

Array
(
[1] => Foo Object
    (
        [pk] => 2
    )

[2] => Foo Object
    (
        [pk] => 3
    )

[3] => Foo Object
    (
        [pk] => 4
    )
Run Code Online (Sandbox Code Playgroud)

)

如果对象具有__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);
    }

}
Run Code Online (Sandbox Code Playgroud)

是否有可能array_uintersect($arr1,$arr2,$somecallback)强制使用Foo::Equals()?从我可以看到转换string发生在调用回调之前.

任何想法如何解决这个问题?

kap*_*apa 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'));
Run Code Online (Sandbox Code Playgroud)