4

I have a array that looks a bit like this

array(
    [0] => array(
        ['id'] => 29
        ['name'] => john
        )
    [1] => array(
        ['id'] => 30
        ['name'] => joe
        ) 
    [2] => array(
        ['id'] => 29
        ['name'] => jake
        ) 
)

And that goes on for a while.

I've found the question elsewhere (here) and (here) But neither works.

With the first one I get the following array

array(
    [0] => 29
    [1] => jake
)

And with te second one it only filters out exact duplicates and not duplicates with jus the same id.

I want all the duplicates with the same id removed from the array, how do I do that?

Community
  • 1
  • 1
Liam de Haas
  • 1,258
  • 3
  • 18
  • 39

3 Answers3

5

Simple with PHP >= 5.5.0:

$result = array_column($array, null, 'id');

Optionally:

$result = array_values(array_column($array, null, 'id'));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
4
$filteredUsers = [];
foreach ($users as $user) {
    $filteredUsers[$user['id']] = $user;
}

// optionally:
// $filteredUsers = array_values($filteredUsers);
deceze
  • 510,633
  • 85
  • 743
  • 889
  • I have in fact posted variations on this answer many many times already, but I can't find any of them at the moment... – deceze Jun 19 '15 at 15:16
2

If you want delete the duplicate and leave one alone:

$array = array(
    array(
        'id' => 29,
        'name' => 'john'
    ),
    array(
        'id' => 30,
        'name' => 'joe'
    ),
    array(
        'id' => 29,
        'name' => 'jake'
    ) 
);

$filter = [];
$array = array_filter($array, function($a) use (&$filter) {
    $ret = !isset($filter[$a['id']]);
    $filter[$a['id']] = true;

    return $ret;
});

Demo.

Otherwise:

$duplicate = array_count_values(array_map(function($i) {
   return $i['id'];
}, $array));

$array = array_filter($array, function($a) use ($duplicate) {
    return $duplicate[$a['id']] <= 1;
});

var_dump($array);

This will print:

array(1) {
  [1]=>
  array(2) {
    ["id"]=>
    int(30)
    ["name"]=>
    string(3) "joe"
  }
}
Federkun
  • 36,084
  • 8
  • 78
  • 90