Home > Article > Backend Development > How Can I Maintain Key Order While Sorting Associative Arrays in PHP Using uasort?
Maintaining Key Order in PHP Sorting with uasort
When sorting an associative array in PHP using the uasort function, it is possible to enforce a stable sort that preserves the original key order, even if multiple keys share the same value.
Solution
Since PHP no longer supports stable sorting by default, a custom function is required:
<code class="php">function mergesort(&$array, $cmp_function = 'strcmp') { // Base cases for arrays of size < 2 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); // Recursively sort the halves mergesort($array1, $cmp_function); mergesort($array2, $cmp_function); // Handle case if $array1 is entirely less than $array2 if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) { $array = array_merge($array1, $array2); return; } // Merge the two sorted arrays $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; }</code>
Usage
Simply use the mergesort function to sort your associative array, passing it as the first argument and an anonymous function for comparing values (optional):
<code class="php">uasort($arr, function($a, $b){ return ($a == $b)?1:($a - $b); });</code>
The above is the detailed content of How Can I Maintain Key Order While Sorting Associative Arrays in PHP Using uasort?. For more information, please follow other related articles on the PHP Chinese website!