Remove duplicates in an array of objects in PHP

2

I have an array of objects and I wanted to know if there is any way to eliminate the duplicates. array_unique() does not detect it.

The solution that works for me is to go through it, take ["tagname"] from another array, eliminate the duplicates by saving its index and, later, remove the elements with that index from the array of objects. But this would be giving too many turns to an object that will contain 100k + elements.

Do you know something more optimal?

Thanks!

var_dump in the object array

array(15) {
  [0]=>
  [...]
  [10]=>
  object(stdClass)#12 (2) {
    ["tagname"]=>
    string(12) "REPEATED_TAG"
    ["category"]=>
    string(7) "DEFAULT"
  }
  [11]=>
  object(stdClass)#13 (2) {
    ["tagname"]=>
    string(4) "TEST"
    ["category"]=>
    string(7) "DEFAULT"
  }
  [14]=>
  object(stdClass)#16 (2) {
    ["tagname"]=>
    string(12) "REPEATED_TAG"
    ["category"]=>
    string(7) "DEFAULT"
  }
  [...]
}
    
asked by Jordi Huertas 30.08.2017 в 10:45
source

2 answers

3

Php itself already has a function in charge of that.

array_unique($array, SORT_REGULAR);

Source
Documentation

    
answered by 30.08.2017 / 10:56
source
2

if this code serves you:

function super_unique($array,$key)

{

$temp_array = array();

foreach ($array as &$v) {

   if (!isset($temp_array[$v[$key]]))

   $temp_array[$v[$key]] =& $v;

}

$array = array_values($temp_array);

return $array;



}

Courtesy of: link

It works as follows: super_unique ($ array, $ parameter to filter);

    
answered by 02.09.2017 в 01:39