具有关联数组的唯一数组 - 删除重复项
我有一个包含一些重复项目的关联数组。例如,我有:
<?
$group_array = array('user_id'=>array(), 'user_first'=>array());
输出如下所示:
Array
(
[user_id] => Array
(
[0] => 594
[1] => 597
[2] => 594
)
[user_first] => Array
(
[0] => John
[1] => James
[2] => John
)
)
我想清理整个数组,以便只有用户 John 才会出现一次(基于 user_id)。
我已尝试以下操作:
<?php
$unique = array_unique($group_array);
print_r($unique);
但它似乎不起作用。还有其他想法如何删除数组中的重复项吗?
任何帮助都会很棒!
I've got an associative array with some duplicate items. For example, I have:
<?
$group_array = array('user_id'=>array(), 'user_first'=>array());
Which outputs something like below:
Array
(
[user_id] => Array
(
[0] => 594
[1] => 597
[2] => 594
)
[user_first] => Array
(
[0] => John
[1] => James
[2] => John
)
)
I'd like to sanitize this entire array so that only the user John will show up once (based on user_id).
I've tried the following:
<?php
$unique = array_unique($group_array);
print_r($unique);
But it does not appear to work. Any other ideas how I can remove the duplicate items in the array?
Any help would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一种方法是找到唯一的 user_id,重要的是它们的数组键,然后仅保留每列中的相应值。
Another approach would be to find the unique
user_id
s, and importantly their array keys, then keep only the corresponding values from each of the columns.有几件事:
array_unique 函数不会递归到子数组中
阅读手册: http: //php.net/manual/en/function.array-unique.php
“当且仅当 (string) $elem1 === (string) $elem2 时,两个元素才被视为相等。换句话说:当字符串表示形式相同时。将使用第一个元素。”
在你的情况下 $elem1 和 $elem2 都是数组
Couple of things:
the array_unique function does not recurse into sub arrays
Read the manual: http://php.net/manual/en/function.array-unique.php
"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."
In your case $elem1 and $elem2 are both arrays
一个可能的解决方案是使用 array_combine(...) 的过滤副作用:
因此我们得到了数组
要恢复原始结构,我们只需提取键和值即可:
结果:
A possible solution is to use the filtering side effect of
array_combine(...)
:So we got the array
To restore the original structure we simply can extract the keys and the values:
Result:
该脚本删除 user_id 上的重复项并保留多个
名字(如果 ID 不同):
输出:
This script removes duplicates on user_id and keeps multiple
firstnames if their ids are different:
output: