1

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.

2 Answers 2

3
$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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

https://www.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.