$a=array(3=>1,6=>3,4=>2,5=>1); asort($a);
打印效果是Array ( [5] => 1 [3] => 1 [4] => 2 [6] => 3 ),
实际需求希望得到Array ( [3] => 1 [5] => 1 [4] => 2 [6] => 3 )
参考https://www.php.net/manual/vote-note.php?id=114535&page=function.uasort&vote=down得到如下解决方法,代码如下
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 == $b) { return 0; } return ($a > $b) ? 1 : -1; } $a = $b = array( 3=>1,6=>3,4=>2,5=>1 ); uasort($a, 'cmp'); print_r($a); stable_uasort($b, 'cmp'); //打印结果正是想要的。 print_r($b);
如果本文对你有帮助,欢迎打赏本站