我如何使用array_unique数组的数组吗? [英] How do I use array_unique on an array of arrays?
问题描述
我有一个数组
Array(
[0] => Array
(
[0] => 33
[user_id] => 33
[1] => 3
[frame_id] => 3
)
[1] => Array
(
[0] => 33
[user_id] => 33
[1] => 3
[frame_id] => 3
)
[2] => Array
(
[0] => 33
[user_id] => 33
[1] => 8
[frame_id] => 8
)
[3] => Array
(
[0] => 33
[user_id] => 33
[1] => 3
[frame_id] => 3
)
[4] => Array
(
[0] => 33
[user_id] => 33
[1] => 3
[frame_id] => 3
)
)
正如你所看到0键是一样的1,3和4和关键2是从他们完全不同。
As you can see key 0 is the same as 1,3 and 4. And key 2 is different from them all.
在运行对他们的array_unique功能,唯一留下的就是
When running the array_unique function on them, the only left is
Array (
[0] => Array
(
[0] => 33
[user_id] => 33
[1] => 3
[frame_id] => 3
)
)
为什么预期array_unique不工作任何想法?
any ideas why array_unique isn't working as expected?
推荐答案
这是因为 array_unique
比较使用字符串比较的项目。从文档:
It's because array_unique
compares items using a string comparison. From the docs:
注:有两个因素被认为是
等于当且仅当(字符串)$ elem1
===(字符串)$ elem2时。在话:当字符串重新presentation是一样的。
第一元件将被使用。
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.
再数组的presentation的字符串是简单的字阵列
,不管其内容。
The string representation of an array is simply the word Array
, no matter what its contents are.
您可以做你想做的事通过以下内容:
You can do what you want to do by using the following:
$arr = array(
array('user_id' => 33, 'frame_id' => 3),
array('user_id' => 33, 'frame_id' => 3),
array('user_id' => 33, 'frame_id' => 8)
);
$arr = array_intersect_key($arr, array_unique(array_map('serialize', $arr)));
//result:
array
0 =>
array
'user_id' => int 33
'user' => int 3
2 =>
array
'user_id' => int 33
'user' => int 8
下面是它如何工作的:
-
每个阵列产品系列化。这个
基于阵列的将是唯一的
内容。
Each array item is serialized. This will be unique based on the array's contents.
这样做的结果是通过 array_unique
运行,
所以只有阵列具有独特的
签名离开了。
The results of this are run through array_unique
,
so only arrays with unique
signatures are left.
array_intersect_key
将采取
独特的项目从钥匙
图/独特的功能(自源数组的键是preserved)和拉
他们出原始源的
数组。
array_intersect_key
will take
the keys of the unique items from
the map/unique function (since the source array's keys are preserved) and pull
them out of your original source
array.
这篇关于我如何使用array_unique数组的数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!