-1

I have a multidimensional array returned by PDO after a query and i'm having a few duplicate results. They're not entirely duplicate, but only one key is duplicate. So:

[0] => 
  'id' => 2,
  'test' => 'My test',
[1] => 
  'id' => 2,
  'test' => 'Another test',
[2] => 
  'id' => 3,
  'test' => 'My tests',

I want to remove the duplicate entries with the same ID value. How can i do this?

hakre
  • 193,403
  • 52
  • 435
  • 836
  • My first thought is to walk over every element in this array and have a second array which would hold the "visited" ids. If you encounter id, which is already in visited, you unset() it. – koressak Jul 07 '11 at 20:21
  • 1
    @JavascriptGOLD, why do u have duplicate IDs in your database?? if it is an **`id`** , it should not be allowed to be duplicate... – Naftali Jul 07 '11 at 20:24
  • It's coming from an INNER JOIN, man. It's not duplicate IDs, each record is different, but same ids appear from each record appear. Like a list of comments and users. – JavascriptGOD Jul 07 '11 at 20:29

2 Answers2

0

You can create a new array with the PDO results...

$newArray = array();
foreach ($pdoArray AS $result) {
    if (isset($newArray[$result['id']])) {
        continue; }
    $newArray[$result['id']] = $result['test'];
}

What this does is adds things to a new array, with the id bing the new array's key. If it finds an array with the same key, it just skips it.

This is a simple answer, you would probably want checks to make sure you get the right value (which of the two IDs do you want to keep?)

Alternatively, if you don't want to keep any of them, build the array, but in addition of doing a continue; you could add the id to a new array (a delete array). Then once the first loop is done, loop thru the delete array and delete the keys:

$newArray = array();
$delete = array();
foreach ($pdoArray AS $result) {
    if (isset($newArray[$result['id']])) {
        $delete[] = $result['id'];
        continue; }
    $newArray[$result['id']] = $result['test'];
}
foreach ($delete AS $del) {
    unset($newArray[$del]); }

OR you can add the ID to the delete arrays key (rather than value) and then do an array_diff_key().

But, it looks to me that you need to re-think your database structure... why do you have duplicate IDs?

blitzmann
  • 7,319
  • 5
  • 23
  • 29
0

Change your query to use GROUP BY id

But in general if it is an id , it should not be allowed to be duplicate.

Naftali
  • 144,921
  • 39
  • 244
  • 303