php php获取多维数组的唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2442230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php getting unique values of a multidimensional array
提问by Mark
Possible Duplicate:
php multi-dimensional array remove duplicate
可能的重复:
php多维数组删除重复
I have an array like this:
我有一个这样的数组:
$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', ),
)
I tried using array_unique, but that doesn't work due to this array being multidimensional, I think.
我尝试使用 array_unique,但由于这个数组是多维的,我认为这不起作用。
Edit: I also need this array to be multi-dimensional and in this format, I can't flatten it.
编辑:我还需要这个数组是多维的,并且在这种格式下,我无法将其展平。
回答by Gumbo
array_uniqueis using string conversion before comparing the values to find the unique values:
array_unique在比较值以查找唯一值之前使用字符串转换:
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.
注意:当且仅当两个元素被认为相等
(string) $elem1 === (string) $elem2。换句话说:当字符串表示相同时。将使用第一个元素。
But an array will always convert to Array:
但是数组总是会转换为Array:
var_dump("Array" === (string) array());
You can solve this by specifying the SORT_REGULARmode in the second parameter of array_unique:
您可以通过在 的第二个参数中指定SORT_REGULAR模式来解决此问题array_unique:
$unique = array_unique($a, SORT_REGULAR);
Or, if that doesn't work, by serializingthe arrays before and unserializingit after calling array_uniqueto find the unique values:
或者,如果这不起作用,请在调用之前序列化数组并在调用以查找唯一值之后对其进行反序列化array_unique:
$unique = array_map('unserialize', array_unique(array_map('serialize', $a)));
回答by Marcx
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);
?>
回答by Sejanus
Use SORT_REGULAR flag.
使用 SORT_REGULAR 标志。
$unique_array = array_unique($a, SORT_REGULAR);
I'm not sure why it helps but it does. At least with php 5.3
我不确定为什么它有帮助,但确实如此。至少使用 php 5.3

