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;
}
}
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.';
}
function Equals(self $other){
return ($this->pk==$other->pk);
}
}
array_uintersect($arr1,$arr2,$somecallback), Foo::Equals()? , , string .
, ?