Php duplicate keys in different objects in an array

I have an array with a number of objects, and I want to search for objects to compare and remove duplicates. Structure example:

Array ( [0] => stdClass Object ( [lrid] => 386755343029 [uu] => website.address.com ) [1] => stdClass Object ( [lrid] => 386755342953 [uu] => website.address.com ) ) 

If the UU key is the website address, and I want to show only the first version, not a duplicate. Any help would be greatly appreciated.

+1
loops php foreach
source share
2 answers
 $sites = array(); foreach ($array as $object) { if (!array_key_exists($object->uu, $sites)) { $sites[$object->uu] = $object; } } 

If you want a "regular array", use array_values() with $sites as an argument.

+3
source share

If the objects are identical, you should just call array_unique ($ array);

http://us2.php.net/manual/en/function.array-unique.php

If the objects are different but have only the same identifier, you can implement the __toString () method (note the two underscores in front) and return (string) $ this-> id; This will call the array_unique function (which leads to the string) to call the magic method you implemented and get only the object identifier.

You may have to implement a magic method to make sure array_unique is not crashing when it tries to pass your objects to strings, I don’t remember.

+1
source share

All Articles