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

时间:2022-07-06 13:02:40

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...

有人可以帮我...

2 个解决方案

#1


39  

The user comments on the array_unique page 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;
}
?>

#2


3  

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(),然后反序列化生成的数组。

#1


39  

The user comments on the array_unique page 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;
}
?>

#2


3  

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(),然后反序列化生成的数组。