[英]Mantain only first instance of each duplicated values in array
Consider the following populated array:考虑以下填充数组:
[
1 => 21
2 => 19
3 => 19
4 => 19
5 => 18
6 => 18
7 => 16
8 => 15
9 => 15
10 => 15
11 => 15
12 => 14
13 => 14
14 => 14
15 => 13
16 => 13
17 => 12
18 => 11
19 => 11
20 => 11
21 => 11
22 => 11
23 => 9
24 => 9
25 => 8
]
I am trying to iterate this array and mantain only one and the first instance of each duplicated value, as well as the key , such as I can have the following output:我正在尝试迭代这个数组,并且只保留一个和每个重复值的第一个实例,以及 key ,例如我可以有以下输出:
[
2 => 19
5 => 18
8 => 15
12 => 14
15 => 13
18 => 11
23 => 9
]
So far, I'm only being able to mantain an erratic instance of each duplicated value, resulting in this output:到目前为止,我只能维护每个重复值的不稳定实例,从而产生以下输出:
[
3 => 19
6 => 18
9 => 15
13 => 14
16 => 13
19 => 11
24 => 9
]
This output I'm receiving using the following code:我使用以下代码收到此输出:
$arrayFiltered = array_unique(array_diff_assoc($array, array_unique($array)));
Based off your updates, I've got this for you.根据您的更新,我为您准备了这个。 It's essentially only returning the value to the
$new
array if it's count is more than 1 (duplicate) within the $array
.如果它在
$new
array 中的计数大于 1(重复),它本质上只会将值返回给$new
$array
。 That's where array_unique()
comes in. It'll clean up everything else and only show you the very first instance of each duplicate, as you require.这就是
array_unique()
用武之地。它会清理其他所有内容,并且仅根据您的需要向您显示每个副本的第一个实例。
$new = array_unique(array_filter($array, function(&$item) use($array){
if(count(array_keys($array, $item)) > 1) {
return $item;
}
}));
Returns:返回:
Array
(
[2] => 19
[5] => 18
[8] => 15
[12] => 14
[15] => 13
[18] => 11
[23] => 9
)
Try using a foreach()
, array_count_values()
, and array_search()
like so:尝试使用
foreach()
、 array_count_values()
和array_search()
如下所示:
$new = array();
$multi = array_count_values($arr);
foreach($multi as $key => $value) {
if($value <= 1)
continue;
$search = array_search($key,$arr);
$new[$search] = $arr[$search];
}
print_r($new);
Gives you:给你:
(
[2] => 19
[5] => 18
[8] => 15
[12] => 14
[15] => 13
[18] => 11
[23] => 9
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.