how to get 1 out of each duplicate elements on an array

32 Views Asked by At

My function store elements in an array like this:

array (
  0 => 
  array (
    'name' => 'Roger',
    'id' => '1',
  ),
  1 => 
  array (
    'name' => 'David',
    'id' => '2',
  ),
  2 => 
  array (
    'name' => 'David',
    'id' => '2',
  ),
)

I used array_unique($myArray), but it returns only the non-duplicate elements.

array (
  0 => 
  array (
    'name' => 'Roger',
    'id' => '1',
  ),
)

I need 1 out of each duplicate elements.

1

There are 1 best solutions below

1
KIKO Software On BEST ANSWER

This is not too difficult and can be solved with basic PHP. Assume that your data is stored in the variable $rows then you can do this:

$output = [];
foreach ($rows as $row) {
   $output[$row['id']] = $row;
}

The result will be in $output. For a live demo see: https://3v4l.org/B8FUK

In case you want normalize keys you can do:

$output = array_values($output);