-1

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.

  • I wouldn't store those names in a 2 dimensional array, if it is really your function, and it only needs to return names. A simpler 1 dimensional array would make more sense and in that case `array_unique()` will also work properly. – KIKO Software Mar 23 '23 at 14:56
  • @KIKOSoftware Doesnt actually store just names. stores some ids an some other things – SOUserNumber613 Mar 23 '23 at 14:58
  • 1
    OK, in that case please make your question reflect that. Also, if possible, use [var_export()](https://www.php.net/manual/en/function.var-export) to create your question, that way we can use the code in your question to create an answer. – KIKO Software Mar 23 '23 at 15:00
  • Updated the anwer. I dont know what you mean by "var_export() to create your question" – SOUserNumber613 Mar 23 '23 at 15:02
  • 1
    It seems you've used `var_dump()` to show us the content of your array. The output of `var_dump()` cannot be used as code. If you use `var_export()` instead you get proper code as output. – KIKO Software Mar 23 '23 at 15:05
  • Updated. I hope that it's clearer now. – SOUserNumber613 Mar 23 '23 at 15:10
  • 1
    Yes, thank you. Doesn't that look better? One final question. Does all the content in one sub-array have to be unique, or can we only look at the names and make those unique in the assumption that the rest will be unique? This makes me think, does the function that returns this 2D array contain a database query? Because it would be much easier to assure that the query only returns unique results than it is to make the results unique afterwards in PHP. – KIKO Software Mar 23 '23 at 15:14
  • It does look way better! Answering your question, I need the id to be unique, it doesnt matter if two elements share the same name if they have different id's. Right now I cant change the query so it needs to be done afterwards. – SOUserNumber613 Mar 23 '23 at 15:19
  • OK, unique id only, that's clear. – KIKO Software Mar 23 '23 at 15:20

1 Answers1

1

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);
KIKO Software
  • 15,283
  • 3
  • 18
  • 33