Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove duplicate values from multidimensional array

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

like image 773
Aadi Avatar asked Aug 30 '10 06:08

Aadi


People also ask

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);


2 Answers

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;
}
?>
like image 186
Russell Dias Avatar answered Sep 24 '22 21:09

Russell Dias


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.

like image 23
Amber Avatar answered Sep 23 '22 21:09

Amber