Tuesday, March 4, 2014

PHP: Remove duplicate value in array

Basic array:

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

Output:
Array
(
    [a] => green
    [0] => red
    [1] => blue
)
Refer site: http://sg3.php.net/array_unique

Multi-dimensional array:
<?php
$date = array(
array('month' => 'Jan', 'year' => '2010'),
array('month' => 'Jan', 'year' => '2010'),
array('month' => 'Jan', 'year' => '2010'),
array('month' => 'Feb', 'year' => '2010'),
array('month' => 'Feb', 'year' => '2010'),
array('month' => 'Mar', 'year' => '2010'),
array('month' => 'Apr', 'year' => '2010'),
array('month' => 'Apr', 'year' => '2010')
);

print_r(super_unique($date,'month'));

function super_unique($array,$key) {

   $temp_array = array();

   foreach ($array as &$v) {

       if (!isset($temp_array[$v[$key]]))

       $temp_array[$v[$key]] =& $v;

   }

   $array = array_values($temp_array);

   return $array;
}
?>
Output:
Array
(
    [0] => Array
        (
            [month] => Jan
            [year] => 2010
        )

    [1] => Array
        (
            [month] => Feb
            [year] => 2010
        )

    [2] => Array
        (
            [month] => Mar
            [year] => 2010
        )

    [3] => Array
        (
            [month] => Apr
            [year] => 2010
        )

)
Refer site: http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php

No comments:

Post a Comment