一個數組:php
$test = array(1 => 0, 99 => 0, 87 => 0, 45 => 0, 67 => 0, 11 => 1, 2 => 0);
使用 asort($test) 排序,結果是:數組
{"67":0,"2":0,"1":0,"45":0,"87":0,"99":0,"11":1}
雖然值爲 1 的鍵排在了最後,可是一樣值爲 0 的鍵,順序跟以前不一樣了。php7
這裏如何保證值爲 0 的順序不變?code
PHP的asort和sort,底層是用快排實現的。沒法保證同等大小的元素的順序。要保證值爲0的順序不變?只能本身實現一個數組排序。對於數組中相等的元素,它們在排序後的順序是未定義的。 (也即相等元素之間的順序是不穩定的)排序
ps:php7返回順序正常的io
<?php function stable_uasort(&$array, $cmp_function) { if(count($array) < 2) { return; } $halfway = count($array) / 2; $array1 = array_slice($array, 0, $halfway, TRUE); $array2 = array_slice($array, $halfway, NULL, TRUE); stable_uasort($array1, $cmp_function); stable_uasort($array2, $cmp_function); if(call_user_func($cmp_function, end($array1), reset($array2)) < 1) { $array = $array1 + $array2; return; } $array = array(); reset($array1); reset($array2); while(current($array1) && current($array2)) { if(call_user_func($cmp_function, current($array1), current($array2)) < 1) { $array[key($array1)] = current($array1); next($array1); } else { $array[key($array2)] = current($array2); next($array2); } } while(current($array1)) { $array[key($array1)] = current($array1); next($array1); } while(current($array2)) { $array[key($array2)] = current($array2); next($array2); } return; } function cmp($a, $b) { if($a['n'] == $b['n']) { return 0; } return ($a['n'] > $b['n']) ? -1 : 1; } $a = $b = array( 'a' => array("l" => "A", "n" => 1), 'b' => array("l" => "B", "n" => 2), 'c' => array("l" => "C", "n" => 1), 'd' => array("l" => "D", "n" => 2), 'e' => array("l" => "E", "n" => 2), ); uasort($a, 'cmp'); print_r($a); stable_uasort($b, 'cmp'); print_r($b); ?>