Associative arrays in PHP store key-value pairs. When sorting such arrays using PHP's built-in sorting functions, it is important to consider whether or not to preserve the original key order. In this article, we will explore the current behavior of sorting in PHP and provide a custom solution for preserving key order.
In PHP versions prior to 4.1.0, the sorting functions, such as asort() and uasort(), provided a stable sort. This means that when multiple keys had the same value, the order of those keys would be preserved in the sorted result. However, starting with PHP 4.1.0, stability is no longer guaranteed.
Since PHP's built-in sorting functions do not support stable sorting, we need to implement our own. The merge sort algorithm is commonly used for this purpose due to its guaranteed O(n*log(n)) time complexity:
<code class="php">function mergesort(&$array, $cmp_function = 'strcmp') { ... // Logic for splitting, merging, and sorting the array ... }</code>
This custom function can be used with uasort() to sort the associative array while preserving the original key order:
<code class="php">uasort($arr, function($a, $b) { return mergesort([$a, $b]); });</code>
<code class="php">$arr = [ 'key-1' => 10, 'key-2' => 20, 'key-3' => 10, 'key-4' => 30, ]; uasort($arr, function($a, $b) { return mergesort([$a, $b]); }); print_r($arr);</code>
Output:
Array ( [key-1] => 10 [key-3] => 10 [key-2] => 20 [key-4] => 30 )
By using the custom stable sort function, the key order of the original array is preserved in the sorted output.
The above is the detailed content of How to Preserve Key Order When Sorting Associative Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!