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

时间:2018-11-20 20:01:07

标签: php arrays equals array-column

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

示例:

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

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

3 个答案:

答案 0 :(得分:0)

array_unique()

示例:

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

答案 1 :(得分:0)

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

$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!

答案 2 :(得分:0)

您可以遍历父数组,序列化每个子数组并将其保存在第三个数组中,然后在循环时,检查每个下一个子数组与第三个数组中保存的所有先前子数组之间是否存在序列。如果存在,请通过键从父阵列中删除当前重复项。下面的函数演示了这一点。

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;
}

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

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

上面的函数扩展了1线性解决方案中实际发生的事情。