Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array with series of objects and I want to search through the objects to compare and remove duplicates. An example of the structure is:

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

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

With the UU key being a website address and I only want to show the first version rather than the duplicate. Any help would be greatly appreciated.

share|improve this question

2 Answers

up vote 3 down vote accepted
$sites = array();
foreach ($array as $object) {
  if (!array_key_exists($object->uu, $sites)) {
    $sites[$object->uu] = $object;
  }
}

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

share|improve this answer

If the objects are identical, you should be able to simply call array_unique($array);

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

If the objects are different but just have the same id's, you can implement the __toString() method (note two underscores in front) and have it return (string)$this->id; That will cause the array_unique function (which casts to string) to call the magic method you implemented and get just the id's of the object.

You may have to implement the magic method anyway to make sure array_unique doesn't fail when it tries to cast your objects to strings, I don't remember.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.