请教一个PHP排序的问题


我要对数组进行数值排序,代码如下:


 $a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
asort($a, SORT_NUMERIC);
var_dump($a);

打印结果如下:


 array(5) {
  'd' =>
  int(10)
  'a' =>
  int(10)
  'c' =>
  int(10)
  'z' =>
  int(10)
  'b' =>
  int(11)
}

问题:

  • 我需要对数值进行排序(已实现)
  • 若数值相同,则数组键的顺序位置不改变,请问如何做到

举例:
上面的数组


 $a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);

根据上面排序后,键的顺序依次为

d => 10, a => 10, c => 10, z => 10, b => 11

我希望能实现的顺序为为

a => 10, z => 10, c => 10, d => 10, b => 11

php 排序

克劳⑨⑨⑧ 10 years, 3 months ago

http://3v4l.org/fsQkS


 function hasort($arr) {
    $a = $b = array();
    foreach($arr as $v => $k) $a[$k][] = $v;
    ksort($a);
    foreach($a as $v => $i) 
        foreach($i as $k) $b[$k] = $v;
    return $b;
}
$a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
$a = hasort($a);
print_r($a);
/**
Array
(
    [a] => 10
    [z] => 10
    [c] => 10
    [d] => 10
    [b] => 11
)
**/

中国杯具帝 answered 10 years, 3 months ago

Your Answer