php获取多维数组的唯一值 [英] php getting unique values of a multidimensional array
问题描述
可能的重复:
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', ),
)
如何删除重复值以便获得此值:
How can I remove the duplicate values so that I get this:
$a = array (
0 => array ( 'value' => 'America', ),
1 => array ( 'value' => 'England', ),
2 => array ( 'value' => 'Australia', ),
4 => array ( 'value' => 'Canada', ),
)
我尝试使用 array_unique,但我认为由于这个数组是多维的,所以这不起作用.
I tried using array_unique, but that doesn't work due to this array being multidimensional, I think.
我还需要这个数组是多维的,在这种格式下,我无法将其展平.
I also need this array to be multi-dimensional and in this format, I can't flatten it.
推荐答案
array_unique
在比较值之前使用字符串转换来查找唯一值:
array_unique
is using string conversion before comparing the values to find the unique values:
注意:当且仅当 (string) $elem1 === (string) $elem2
时才认为两个元素相等.换句话说:当字符串表示相同时.将使用第一个元素.
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.
但是数组总是会转换为Array
:
But an array will always convert to Array
:
var_dump("Array" === (string) array());
你可以通过在array_unique
的第二个参数中指定SORT_REGULAR模式来解决这个问题:
You can solve this by specifying the SORT_REGULAR mode in the second parameter of array_unique
:
$unique = array_unique($a, SORT_REGULAR);
或者,如果这不起作用,通过序列化之前的数组和在调用array_unique
后反序列化以找到唯一值:
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)));
这篇关于php获取多维数组的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!