Will array_unique work also with array of objects?

Posted by Richard Knop on Stack Overflow See other posts from Stack Overflow or by Richard Knop
Published on 2010-12-22T08:49:11Z Indexed on 2010/12/22 8:54 UTC
Read the original article Hit count: 179

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about php5