Will array_unique work also with array of objects?
- by Richard Knop
Is there a better way than using array-walk in combination with unserialize?
I have two arrays which contain objects. The objects can be same or can be different. I want to merge both arrays and keep only unique objects.
This seems to me like a very long solution for something so trivial. Is there any other way?
class Dummy
{
private $name;
public function __construct($theName) {$this->name=$theName;}
}
$arr = array();
$arr[] = new Dummy('Dummy 1');
$arr[] = new Dummy('Dummy 2');
$arr[] = new Dummy('Dummy 3');
$arr2 = array();
$arr2[] = new Dummy('Dummy 1');
$arr2[] = new Dummy('Dummy 2');
$arr2[] = new Dummy('Dummy 3');
function serializeArrayWalk(&$item)
{
$item = serialize($item);
}
function unSerializeArrayWalk(&$item)
{
$item = unserialize($item);
}
$finalArr = array_merge($arr, $arr2);
array_walk($finalArr, 'serializeArrayWalk');
$finalArr = array_unique($finalArr);
array_walk($finalArr, 'unSerializeArrayWalk');
var_dump($finalArr);