14

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!

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

Amber
  • 507,862
  • 82
  • 626
  • 550
Aadi
  • 6,959
  • 28
  • 100
  • 145
  • must a duplicate of: http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php or http://stackoverflow.com/questions/1861682/php-multi-dimensional-array-remove-duplicate – Vaibhav Gupta Aug 30 '10 at 06:27
  • 1
    All functions like array_unique() are just a syntax sugar for really simple loops. With very little effort you can do it yourself for sure. Try to be more devious. Programming is not always just copy-pasting, sometimes it require more intelligent work. – Your Common Sense Aug 30 '10 at 06:48
  • 1
    This more recent question has even better solutions: http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php – 4levels Dec 05 '16 at 10:55

2 Answers2

40

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.

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;
}
?>
Russell Dias
  • 70,980
  • 5
  • 54
  • 71
  • Russell i am able to remove duplicated using this function but have 1 problem how to re index the array inside the array..hope you can shed light – Brownman Revival May 02 '15 at 07:18
  • 1
    A cleaner solution, taken from http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php: $input = array_map("unserialize", array_unique(array_map("serialize", $input))); – 4levels Dec 05 '16 at 10:56
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.

Amber
  • 507,862
  • 82
  • 626
  • 550