Thursday, March 3, 2011

How to remove duplicate values from a multi-dimensional array in PHP

How can I remove duplicate values from a multi-dimensional array in PHP?

Example array:

Array
(
    [0] => Array
 (
     [0] => abc
     [1] => def
 )

    [1] => Array
 (
     [0] => ghi
     [1] => jkl
 )

    [2] => Array
 (
     [0] => mno
     [1] => pql
 )

    [3] => Array
 (
     [0] => abc
     [1] => def
 )

    [4] => Array
 (
     [0] => ghi
     [1] => jkl
 )

    [5] => Array
 (
     [0] => mno
     [1] => pql
 )

)
From stackoverflow
  • The user comments on the array_unique() documentation have many solutions to this. Here is one of them:

    kenrbnsn at rbnsn dot com
    27-Sep-2005 12:09

    Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.

    This function uses the serialize, array_unique, and unserialize functions to do the work.

        function multi_unique($array) {
            foreach ($array as $k=>$na)
                $new[$k] = serialize($na);
            $uniq = array_unique($new);
            foreach($uniq as $k=>$ser)
                $new1[$k] = unserialize($ser);
            return ($new1);
        }

    This is from http://ca3.php.net/manual/en/function.array-unique.php#57202.

  • Another way. Will preserve keys as well.

    function array_unique_multidimensional($input)
    {
        $serialized = array_map('serialize', $input);
        $unique = array_unique($serialized);
        return array_intersect_key($input, $unique);
    }
    
  • Here is another, another way. No intermediate variables are saved.

    We used this to de-duplicate results from a variety of overlapping queries.

    $input = array_map("unserialize", array_unique(array_map("serialize", $input)));
    
  • An easy to read solution, probably not the most efficient:

    function arrayUnique($myArray){
        if(!is_array($myArray))
            return $myArray;
    
        foreach ($myArray as &$myvalue){
            $myvalue=serialize($myvalue);
        }
    
        $myArray=array_unique($myArray);
    
        foreach ($myArray as &$myvalue){
            $myvalue=unserialize($myvalue);
        }
    
        return $myArray;
    
    } 
    

0 comments:

Post a Comment