Bhaskar Wankhede
Bhaskar Wankhede

Reputation: 69

Removed rows from a 2d array if a column value has been encountered more than once

How can I check if the values are unique in an array based on the key value?

Below is the output of the array. I want to remove duplicate values based on the "id" key. If you check below, the 2nd & 3rd array are same except for the "role" value. Because of this, array_unique is not working on this array.

[
    [
        'id' => '1521422',
        'name' => 'David Alvarado',
        'role' => 'associate producer  ',
    ],
    [
        'id' => '0098210',
        'name' => 'Cristian Bostanescu',
        'role' => 'line producer: Romania  (as Cristi Bostanescu)',
    ],
    [
        'id' => '1266015',
        'name' => 'Bruno Hoefler',
        'role' => 'co-producer  ',
    ],
    [
        'id' => '1266015',
        'name' => 'Bruno Hoefler',
        'role' => 'executive producer  ',
    ],
    [
        'id' => '1672379',
        'name' => 'Alwyn Kushner',
        'role' => 'associate producer  ',
    ],
]

Upvotes: 2

Views: 376

Answers (3)

anubhava
anubhava

Reputation: 785058

You can use this code:

// assuming $arr is your original array
$narr = array();
foreach($arr as $key => $value) {
   //$narr[json_encode($value)] = $key;
   if (!array_key_exists($value["id"], $narr))
      $narr[$value["id"]] = $key;
}
$narr = array_flip($narr);
foreach($arr as $key => $value) {
   if (!array_key_exists($key, $narr))
      unset($arr[$key]);
}
print_r($arr); // will have no duplicates

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Basically you want to implement a variation of array_unique that does what you want:

function array_unique_multi($arr,$key='id') {
    // $arr is the array to work on
    // $key is the key to make unique by
    $ret = Array();
    foreach($arr as $v) {
        if( !isset($ret[$v[$key]])) $ret[$v[$key]] = $k;
    }
    return array_values($ret);
}

Upvotes: 1

TimWolla
TimWolla

Reputation: 32701

Try this one:

<?php
$array = array(
    array('id' => 1, 'text' => 'a'),
    array('id' => 2, 'text' => 'b'),
    array('id' => 1, 'text' => 'c'),
    array('id' => 3, 'text' => 'd')
);
$array = array_filter($array, function ($item) {
    static $found = array();
    if (isset($found[$item['id']])) return false;
    $found[$item['id']] = true;
    return true;
});

var_dump($array);

This works as of PHP 5.3 (because of the closure and static statement).

cf. http://php.net/manual/en/function.array-filter.php for more information. I tested the statement within loops, it works there as well.

Upvotes: 3

Related Questions