【问题标题】:How can I check and delete duplicate arrays?如何检查和删除重复的数组?
【发布时间】:2019-04-23 08:24:21
【问题描述】:

如何检查和删除重复的数组?

例子:

$a = array(
   array(
      'id' => 1,
      'name' => 'test'
   ),
   // Next array is equal to first, then delete
   array(
      'id' => 1,
      'name' => 'test'
   ), 
   // Different array, then continue here
   array(
      'id' => 2,
      'name' => 'other'
   )
);

如果数组相同,则删除重复的,只得到一个数组。

【问题讨论】:

标签: php arrays equals array-column


【解决方案1】:

array_unique()

例子:

$array = array(1, 2, 2, 3);
    $array = array_unique($array); // Array is now (1, 2, 3)

【讨论】:

【解决方案2】:

您可以使用存储序列化数组的查找表。如果查找表中已经存在一个数组,则您有一个重复,可以拼接出键:

$a = array(
   array(
      'id' => 1,
      'name' => 'test'
   ),
   array(
      'id' => 1,
      'name' => 'test'
   ), 
   array(
      'id' => 2,
      'name' => 'other'
   )
);

$seen = [];

for ($i = count($a) - 1; $i >= 0; $i--) {
    if (array_key_exists(json_encode($a[$i]), $seen)) {
        array_splice($a, $i, 1);
    }
    else {
        $seen[json_encode($a[$i])] = 1;
    }
}

print_r($a);

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => test
        )

    [1] => Array
        (
            [id] => 2
            [name] => other
        )

)

Try it!

【讨论】:

    【解决方案3】:

    您可以遍历父数组,序列化每个子数组并将其保存在第三个数组中,并在循环时检查每个下一个子数组的序列是否存在于保存在第三个数组中的所有先前子数组.如果存在,则按键从父数组中删除当前副本。下面的函数演示了这一点。

    function remove_duplicate_nested_arrays($parent_array)
    
      $temporary_array = array(); // declare third, temporary array.
    
      foreach($parent_array as $key =>  $child_array){ // loop through parent array
        $child_array_serial = serialize($child_array); // serialize child each array
        if(in_array($child_array_serial,$temporary_array)){ // check if child array serial exists in third array
          unset($parent_array[$key]); // unset the child array by key from parent array if it's serial exists in third array
          continue;
        }
        $temporary_array[] = $child_array_serial; // if this point is reached, the serial of child array is not in third array, so add it so duplicates can be detected in future iterations.
      }
      return $parent_array;
    }
    

    这也可以在 1 行中实现,使用 @Jose Carlos Gp 的建议如下:

    $b = array_map('unserialize', array_unique(array_map('serialize', $a)));
    

    上述功能扩展了 1 班轮解决方案中实际发生的情况。

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 2021-01-11
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多