如何在PHP中有着一个稳定的排序与arsort()? [英] How to have a stable sort in PHP with arsort()?
问题描述
我需要进行排序PHP中的数组基于价值,数组用于键和值的一些数字,例如像这样的:
$ a =阵列(70 =大于1,82 =大于5,61 => 3,55 =大于1,34 => 2,53 =&GT 2,21 =→4,13 =大于5);
我喜欢这样的顺序来排序
阵列
(
[82] =>五
[13] =>五
[21] => 4
[61] => 3
[34] => 2
[53] => 2
[70] => 1
[55] => 1
)
我用 arsort
和它的工作,但有一个问题,因为此功能进行改变defult分类键并排序数组:
阵列
(
[13] =>五
[82] =>五
[21] => 4
[61] => 3
[53] => 2
[34] => 2
[55] => 1
[70] => 1
)
构造一个新的数组,其元素是原数组的键,值也的位置是:
$ TEMP =阵列();
$ I = 0;
的foreach($数组$关键=> $值){
$温度[] =阵列($ I,$键,$值);
$ I ++;
}
然后排序使用用户定义的顺序,是以原来的位置考虑:
uasort($温度,功能($ A,$ B){
返回$一个[2] == $ B [2]? ($一个[0]≥$ B [0]):($一个[2]所述; $ B [2] 1:α-1);
});
最后,将其转换回原始关联数组:
$阵列=阵列();
的foreach($温度为$ VAL){
$阵列[$ VAL [1] = $ VAL [2];
}
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);
i like to sort it like this:
Array
(
[82] => 5
[13] => 5
[21] => 4
[61] => 3
[34] => 2
[53] => 2
[70] => 1
[55] => 1
)
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];
}
这篇关于如何在PHP中有着一个稳定的排序与arsort()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!