gpt4 book ai didi

php - 使用 PHP 的 uasort 进行排序时保留键顺序(稳定排序)

转载 作者:IT王子 更新时间:2023-10-28 23:46:51 26 4
gpt4 key购买 nike

这个问题实际上是受 SO 上的另一个问题启发的,我想稍微扩展一下。

在 PHP 中有一个关联数组是否可以对其值进行排序,但在值相等的情况下,可以使用 PHP 的一个(或多个)内置排序函数来保留原始键顺序?

这是我用来测试可能解决方案的脚本(还没有找到):

<?php
header('Content-type: text/plain');
for($i=0;$i<10;$i++){
$arr['key-'.$i] = rand(1,5)*10;
}
uasort($arr, function($a, $b){
// sort condition may go here //
// Tried: return ($a == $b)?1:($a - $b); //
// Tried: return $a >= $b; //
});
print_r($arr);
?>

陷阱:因为键是在原始数组中排序的,所以请不要试图建议任何按键排序以恢复到原始顺序。我用它们制作了示例,以便更容易在输出中直观地检查它们的顺序。

最佳答案

PHP does not support stable sort after PHP 4.1.0 ,您需要编写自己的函数。

这似乎可以满足您的要求:http://www.php.net/manual/en/function.usort.php#38827

As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal.

Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)).

<?php
function mergesort(&$array, $cmp_function = 'strcmp') {
// Arrays of size < 2 require no action.
if (count($array) < 2) return;
// Split the array in half
$halfway = count($array) / 2;
$array1 = array_slice($array, 0, $halfway);
$array2 = array_slice($array, $halfway);
// Recurse to sort the two halves
mergesort($array1, $cmp_function);
mergesort($array2, $cmp_function);
// If all of $array1 is <= all of $array2, just append them.
if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
$array = array_merge($array1, $array2);
return;
}
// Merge the two sorted arrays into a single sorted array
$array = array();
$ptr1 = $ptr2 = 0;
while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
$array[] = $array1[$ptr1++];
}
else {
$array[] = $array2[$ptr2++];
}
}
// Merge the remainder
while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
return;
}
?>

此外,您可能会发现 this forum thread有趣。

关于php - 使用 PHP 的 uasort 进行排序时保留键顺序(稳定排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4353739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com