Preserving Key Order in PHP Sorting
Question:
Can we sort an associative array in PHP, preserving the original key order when values are equal, using built-in sorting functions?
Background:
PHP's sort functions such as uasort do not offer stable sorting, meaning the order of elements with equal values may change after sorting.
Answer:
Unfortunately, PHP does not officially support stable sorting after version 4.1.0. Therefore, implementing a custom function is necessary to achieve this.
Custom Function:
One solution is to implement a merge sort function, which guarantees O(n*log(n)) complexity and maintains key order. Here's an example of a merge sort function (mergesort):
<code class="php">function mergesort(&$array, $cmp_function = 'strcmp') { // Handle small arrays if (count($array) < 2) return; // Split the array into two parts $halfway = count($array) / 2; $array1 = array_slice($array, 0, $halfway); $array2 = array_slice($array, $halfway); // Recursively sort the two halves mergesort($array1, $cmp_function); mergesort($array2, $cmp_function); // Merge the sorted halves into the original 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++]; }</code>
By using this function, you can sort your associative array while maintaining the original key order for elements with equal values.
Additional Resources:
The above is the detailed content of Can PHP\'s built-in sorting functions preserve key order when sorting associative arrays with equal values?. For more information, please follow other related articles on the PHP Chinese website!