Skip to content
Advertisement

Remove two dimentional array elements(except first match) which array specific value are same/unique

For example, I have an following two dimentional array is below,

$a = array(
    "one" => array (
        "id" => 111,
        "name" => "Jhon"
    ),
    "two" => array(
        "id" => 222,
        "name" => "Adam"
    ),
    "three" => array(
        "id" => 111,
        "name" => "Mark"
    ),
    "four" => array(
        "id" => 125,
        "name" => "Jhon"
    ),
    "five" => array(
        "id" => 111,
        "name" => "Jhon"
    ),
    "six" => array(
        "id" => 222,
        "name" => "Rock"
    ),
);

I would like to remove array(except first match) which two dimensional array values are same/unique. For example, I would like to remove all of the arrays(except first match) which id keys values are same. As, array id keys values 111(has array count 3) and 222(has array count 2). So after removing the unique key id the result array should be following,

$a = array(
    "one" => array (
        "id" => 111,
        "name" => "Jhon"
    ),
    "two" => array(
        "id" => 222,
        "name" => "Adam"
    ),
    "four" => array(
        "id" => 125,
        "name" => "Jhon"
    ),
);

Advertisement

Answer

You need to keep an array with added keys. You could use array_filter() to remove unnecessary rows.

Code: (demo)

$array = [
    "one"   => ["id" => 111, "name" => "Jhon"],
    "two"   => ["id" => 222, "name" => "Adam"],
    "three" => ["id" => 111, "name" => "Mark"],
    "four"  => ["id" => 125, "name" => "Jhon"],
    "five"  => ["id" => 111, "name" => "Jhon"],
    "six"   => ["id" => 222, "name" => "Rock"],
];

// store added IDs
$added = [];

// filter array (need to pass $added as reference to be updated)
$output = array_filter($array, function($item) use (&$added) 
{
    // shortcut for readability
    $id = $item['id'];  
    // Check if id already exists
    if (isset($added[$id])) { return false; } 
    // add to reference
    $added[$id] = true; 
    // add to final array
    return true; 
});

unset($added); // no longer needed.

var_dump($output);

Output:

array(3) {
  ["one"]=>
  array(2) {
    ["id"]=>
    int(111)
    ["name"]=>
    string(4) "Jhon"
  }
  ["two"]=>
  array(2) {
    ["id"]=>
    int(222)
    ["name"]=>
    string(4) "Adam"
  }
  ["four"]=>
  array(2) {
    ["id"]=>
    int(125)
    ["name"]=>
    string(4) "Jhon"
  }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement