数组与关联数组唯一 - 删除重复 [英] Array Unique with Associative Array - Remove Duplicates
本文介绍了数组与关联数组唯一 - 删除重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<?
$ group_array = array('user_id'=> array(),'user_first'=> array());
哪些输出如下:
Array
(
[user_id] => Array
(
[0] => 594
[1] = > 597
[2] => 594
)
[user_first] =>数组
(
[0] =&
[1] => James
[2] => John
)
)
我想对整个数组进行清理,以便只有用户John才会显示一次(基于user_id)。
我已经尝试了以下内容:
<?php
$ unique = array_unique($ group_array);
print_r($ unique);
但它似乎不起作用。任何其他想法如何可以删除数组中的重复项?
任何帮助都会很棒!
解决方案
另一种方法是找到唯一的 user_id
s,重要的是它们的数组键,然后只保留每个列。
$ group_array = array(
'user_id'=>数组(594,597,594,598 ),
'user_first'=>数组('John','James','John','John'),
);
//查找唯一的user_ids
$ uniques = array_unique($ group_array ['user_id']);
//只保留unity
foreach($ group_array as $ column => $ collection){
$ group_array [$ column] = array_intersect_key($ collection,$ uniques );
}
print_r($ group_array);
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!
解决方案
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.
$group_array = array(
'user_id' => array(594, 597, 594, 598 ),
'user_first' => array('John', 'James', 'John', 'John'),
);
// Find unique user_ids
$uniques = array_unique($group_array['user_id']);
// Keep only the uniques
foreach ($group_array as $column => $collection) {
$group_array[$column] = array_intersect_key($collection, $uniques);
}
print_r($group_array);
这篇关于数组与关联数组唯一 - 删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文