Comparing Arrays of Objects

I am looking for a short way to compare arrays of objects in PHP. I know that I can just check the dimensional arrays and then skip one array looking for each object in the second array, but I thought it would be better to use one or more array comparison functions.

I tested a couple of arrays of objects, and the main problem I am facing is that the array comparison functions insist on comparing the elements like strings, for example:

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

exits

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

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

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

)

This is great if objects have methods __toString()and if these methods __toString()return a unique identifier and never ''.

But what happens if it is not, say for such an object:

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 .

, ?

+5
1

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

All Articles