php getting unique values of a multidimensional array [duplicate]
array_unique
is using string conversion before comparing the values to find the unique values:
Note: Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2
. In words: when the string representation is the same. The first element will be used.
But an array will always convert to Array
:
var_dump("Array" === (string) array());
You can solve this by specifying the SORT_REGULAR mode in the second parameter of array_unique
:
$unique = array_unique($a, SORT_REGULAR);
Or, if that doesn’t work, by serializing the arrays before and unserializing it after calling array_unique
to find the unique values:
$unique = array_map('unserialize', array_unique(array_map('serialize', $a)));
Here :)
<?php
$a = array (
0 => array ( 'value' => 'America', ),
1 => array ( 'value' => 'England', ),
2 => array ( 'value' => 'Australia', ),
3 => array ( 'value' => 'America', ),
4 => array ( 'value' => 'England', ),
5 => array ( 'value' => 'Canada', ),
);
$tmp = array ();
foreach ($a as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
print_r ($tmp);
?>