简体   繁体   English

根据2个值从多维数组中删除重复项

[英]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. 具有SORT_REGULAR标志的array_unique检查所有三个值。 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: 使用foreach循环和array_values函数的简单解决方案:

$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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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