按值对关联数组进行降序排序,并在值相同时保留顺序 [英] Sort an associative array by value in descending and preserve order when values are same
问题描述
我想对一个关联数组进行排序,并且有一个内置函数来实现相同的效果. arsort()
,但是此函数的问题在于,当值相同时,它不会保持原始键顺序.例如
I want to sort an associative array and there is an inbuilt function to achieve the same viz. arsort()
, but the problem with this function is that it doesn't maintain the original key order when values are same.
e.g.
$l = [
'a' => 1,
'b' => 2,
'c' => 2,
'd' => 4,
'e' => 5,
'f' => 5
];
我想要的结果是:
$l = [
'e' => 5,
'f' => 5,
'd' => 4,
'b' => 2,
'c' => 2,
'a' => 1
];
arsort()
以降序给出结果,但是当值相同时,它将随机排列元素.这个问题不是 PHP数组多重排序-按值的重复项然后按密钥?.在这个问题中,它要求按字母顺序对相同的数值进行排序,但是在我的问题中,我要的是如果值相同,则按照原始顺序对值进行排序.
arsort()
gives the result in descending order but it randomly arranges the element when values are same.
This question is not a duplicate of PHP array multiple sort - by value then by key?. In that question it is asking for same numeric value to be sorted alphabetically but in my question I am asking values to sorted according to the original order if they are same.
推荐答案
可能有更有效的方法,但是我认为这应该可以在相同值的组中保持原始键顺序.我将从这个数组开始,例如:
There is probably a more efficient way to do this, but I think this should work to maintain the original key order within groups of the same value. I'll start with this array for example:
$l = [ 'a' => 1, 'b' => 2, 'c' => 2, 'd' => 4, 'g' => 5, 'e' => 5, 'f' => 5 ];
-
按值对数组进行分组:
Group the array by value:
foreach ($l as $k => $v) {
$groups[$v][] = $k;
}
由于 foreach
循环顺序读取数组,因此将以正确的顺序将键插入其各自的组中,这将产生:
Because the foreach
loop reads the array sequentially, the keys will be inserted in their respective groups in the correct order, and this will yield:
[1 => ['a'], 2 => ['b', 'c'], 4 => ['d'], 5 => ['g', 'e', 'f'] ];
按键以降序对组进行排序:
sort the groups in descending order by key:
krsort($groups);
使用嵌套循环从分组数组中重新组合排序后的数组:
Reassemble the sorted array from the grouped array with a nested loop:
foreach ($groups as $value => $group) {
foreach ($group as $key) {
$sorted[$key] = $value;
}
}
这篇关于按值对关联数组进行降序排序,并在值相同时保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!