感谢回答,看到官方手册已经提供了方法:
If you want to keep the order when two members compare as equal, use this.
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);
?>