如何使用 arsort() 在 PHP 中进行稳定排序? [英] How to have a stable sort in PHP with arsort()?
本文介绍了如何使用 arsort() 在 PHP 中进行稳定排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在php中根据值对数组进行排序,数组使用一些数字作为键和值,例如:
i need to sort an array in php based on value, array use some numbers for keys and values, for example like this:
$a = array(70 => 1 ,82 => 5 ,61 => 3 ,55 => 1 ,34 => 2 ,53 => 2 ,21 => 4 ,13 => 5);
我喜欢这样排序:
Array
(
[82] => 5
[13] => 5
[21] => 4
[61] => 3
[34] => 2
[53] => 2
[70] => 1
[55] => 1
)
我使用了 arsort
并且它工作了,但是有一个问题,因为这个函数将默认排序的 keys 和排序数组更改为:
i used arsort
and it worked, but there is a problem because this function make change defult sorted keys and sort array to:
Array
(
[13] => 5
[82] => 5
[21] => 4
[61] => 3
[53] => 2
[34] => 2
[55] => 1
[70] => 1
)
推荐答案
构造一个新数组,其元素是原始数组的键、值和位置:
Construct a new array whose elements are the original array's keys, values, and also position:
$temp = array();
$i = 0;
foreach ($array as $key => $value) {
$temp[] = array($i, $key, $value);
$i++;
}
然后使用考虑原始位置的用户定义顺序进行排序:
Then sort using a user-defined order that takes the original position into account:
uasort($temp, function($a, $b) {
return $a[2] == $b[2] ? ($a[0] - $b[0]) : ($a[2] < $b[2] ? 1 : -1);
});
最后,将其转换回原来的关联数组:
Finally, convert it back to the original associative array:
$array = array();
foreach ($temp as $val) {
$array[$val[1]] = $val[2];
}
这篇关于如何使用 arsort() 在 PHP 中进行稳定排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文