简体   繁体   English

按值降序对关联数组进行排序,并在值相同时保留顺序

[英]Sort an associative array by value in descending and preserve order when values are same

I want to sort an associative array and there is an inbuilt function to achieve the same viz. 我想对一个关联数组进行排序,并且有一个内置函数来实现相同的viz。 arsort() , but the problem with this function is that it doesn't maintain the original key order when values are same. arsort() ,但此函数的问题是,当值相同时,它不会保持原始键顺序。 eg 例如

$l = [
    'a' => 1,
    'b' => 2,
    'c' => 2,
    'd' => 4,
    'e' => 5,
    'f' => 5
];

The result which I want is : 我想要的结果是:

$l = [
    'e' => 5,
    'f' => 5,
    'd' => 4,
    'b' => 2,
    'c' => 2,
    'a' => 1
];

arsort() gives the result in descending order but it randomly arranges the element when values are same. arsort()以降序给出结果,但在值相同时随机排列元素。 This question is not a duplicate of PHP array multiple sort - by value then by key? 这个问题不是PHP数组多重排序的重复- 按值然后按键? . 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 ]; 
  1. Group the array by value: 按值对数组进行分组:

     foreach ($l as $k => $v) { $groups[$v][] = $k; } 

    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: 因为foreach循环按顺序读取数组,所以键将以正确的顺序插入到它们各自的组中,这将产生:

     [1 => ['a'], 2 => ['b', 'c'], 4 => ['d'], 5 => ['g', 'e', 'f'] ]; 
  2. sort the groups in descending order by key: 按键按降序对组进行排序:

     krsort($groups); 
  3. Reassemble the sorted array from the grouped array with a nested loop: 使用嵌套循环从分组数组重新组装已排序的数组:

     foreach ($groups as $value => $group) { foreach ($group as $key) { $sorted[$key] = $value; } } 

You can use array_multisort . 您可以使用array_multisort The function can be a bit confusing, and really hard to explain, but it orders multiple arrays, and the first array provided gets sorted based on the order of subsequent arrays. 该函数可能有点令人困惑,并且很难解释,但它会对多个数组进行排序,并且提供的第一个数组会根据后续数组的顺序进行排序。

Try: 尝试:

array_multisort($l, SORT_DESC, array_keys($l));

See the example here: https://3v4l.org/oV8Od 请参阅此处的示例: https//3v4l.org/oV8Od

It sorts the array by values descending, then is updated by the sort on the keys of the array. 它按降序值对数组进行排序,然后通过数组键上的排序进行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM