dragon071111
dragon071111
2017-03-09 20:10
浏览 55
已采纳

基于2个值从多维数组中删除重复项

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doumen9709
    doumen9709 2017-03-09 20:18
    已采纳

    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
            )
    )
    
    点赞 评论
  • dongzhun4898
    dongzhun4898 2017-03-09 20:18

    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;
        }
    }
    
    点赞 评论
  • dtgu21994537
    dtgu21994537 2017-03-09 20:28

    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));
    
    点赞 评论

相关推荐