比较对象的数组 [英] Comparing arrays of objects

查看:96
本文介绍了比较对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在PHP中比较对象数组的简洁的方式。我知道我可以只检查同等大小的数组,然后遍历一个阵列寻找第二个数组中的每个对象,但我认为这将是更好的使用数组比较函数的一个或多个。

I'm looking for a succinct way of comparing arrays of objects in PHP. I know I could just check for equal sized arrays and then loop through one array looking for each object in the second array, but I thought it would be nicer to use one or more of the array comparison functions.

我测试对象的一对夫妇的数组和我来面对的主要问题是,数组比较功能坚持比较元素字符串,这样

I've tested a couple arrays of objects and the main problem I'm coming up against is that the array comparison functions insist on comparing elements as strings, like this:

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()方法返回一个唯一的标识符永不

That's fine if the objects have __toString() methods and if those __toString() methods return a unique identifier and never ''.

但如果不是这种情况会发生什么,说像这样的对象:

But what happens if that's not the case, say for an object like this:

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)强制使用 ::富的Equals()?从我所看到的转换为字符串出现回调被调用之前。

Is it possible to do array_uintersect($arr1,$arr2,$somecallback) that forces the use of Foo::Equals()? From what I can see the conversion to string happens before the callback is called.

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

Any ideas how to get around this?

推荐答案

是的,你可以使用 array_uintersect 这一点。

Yes, you can use array_uintersect for this.

一些示例code:

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'));

这篇关于比较对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆