简体   繁体   中英

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this

$array = array(
  array("John","Smith","1"),
  array("Bob","Barker","2"),
  array("Will","Smith","2"),
  array("Will","Smith","4")
);

In the end I want the array to look like this

$array = array(
  array("John","Smith","1"),
  array("Bob","Barker","2"),
  array("Will","Smith","2")
);

The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.

Simple solution using foreach loop and array_values function:

$arr = array(
          array("John","Smith","1"), array("Bob","Barker","2"), 
          array("Will","Smith","2"), array("Will","Smith","4")
);

$result = [];
foreach ($arr as $v) {
    $k = $v[0] . $v[1];  // considering first 2 values as a unique key
    if (!isset($result[$k])) $result[$k] = $v;
}

$result = array_values($result);
print_r($result);

The output:

Array
(
    [0] => Array
        (
            [0] => John
            [1] => Smith
            [2] => 1
        )

    [1] => Array
        (
            [0] => Bob
            [1] => Barker
            [2] => 2
        )

    [2] => Array
        (
            [0] => Will
            [1] => Smith
            [2] => 2
        )
)

Sample code with comments:

// array to store already existing values
$existsing = array();
// new array
$filtered = array();

foreach ($array as $item) {
    // Unique key
    $key = $item[0] . ' ' . $item[1];

    // if key doesn't exists - add it and add item to $filtered
    if (!isset($existsing[$key])) {
        $existsing[$key] = 1;
        $filtered[] = $item;
    }
}

For fun. This will keep the last occurrence and eliminate the others:

$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
  • Map the array and build a key from the first to entries of the sub array
  • Use the returned array as keys in the new array and original as the values

If you want to keep the first occurrence then just reverse the array before and after:

$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
                                               $array), $array));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM