PHP 从多维数组中删除重复值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3598298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:21:40  来源:igfitidea点击:

PHP remove duplicate values from multidimensional array

phparraysmultidimensional-array

提问by Aadi

We can use array_unique()for remove duplicate entry from a single multidimensional array in php.Is it possible to use with multidimensional array? It is not working for me!

我们可以array_unique()用于从 php 中的单个多维数组中删除重复条目。是否可以与多维数组一起使用?它不适合我!

Here's what the array looks like

这是数组的样子

Array (
    [0] => Array ( [0] => 1001 [1] => john [2] => example )
    [1] => Array ( [0] => 1002 [1] => test [2] => dreamz )
    [2] => Array ( [0] => 1001 [1] => john [2] => example )
    [3] => Array ( [0] => 1001 [1] => example [2] => john )
    [4] => Array ( [0] => 1001 [1] => john [2] => example )
)

Anybody can please help me...

任何人都可以请帮助我...

回答by Russell Dias

The user comments on the array_uniquepage do shed some light on this. You will most likely find some hidden gems in those comments - its a very handy documentation.

array_unique页面上的用户评论确实对此有所了解。您很可能会在这些评论中找到一些隐藏的宝石 - 这是一个非常方便的文档。

Just a quick browser through revealed the following to remove duplicates from a multi dimensional array:

只是一个快速浏览器通过显示以下内容从多维数组中删除重复项:

<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>

回答by Amber

You could serialize the sub-arrays (via serialize()) into a new array, then run array_unique()on that, and then unserialize the resulting set of arrays.

您可以将子数组(通过serialize())序列化为一个新数组,然后array_unique()在该数组上运行,然后对结果数组进行反序列化。