Can you Preserve Key Order While Sorting Associative Arrays in PHP?

Susan Sarandon
Release: 2024-11-02 20:12:31
Original
179 people have browsed it

Can you Preserve Key Order While Sorting Associative Arrays in PHP?

Preserving Key Order During Sorting with PHP's uasort

Query:

Is it possible to sort the values of an associative array in PHP while maintaining the original order of keys, using PHP's built-in sorting functions?

Challenge:

To achieve a stable sort where equal values retain their initial key order, a custom sorting function must be employed since PHP does not support stable sorting natively.

Solution:

A custom merge sort, which guarantees O(n*log(n)) complexity and maintains stability, can be used:

<code class="php">function mergesort(&$array, $cmp_function = 'strcmp') {
    // Handle base cases
    if (count($array) < 2) return;
    
    // Split the array into halves
    $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);
    
    // Merge the sorted halves
    $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 remaining elements
    while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
    while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
}</code>
Copy after login

Alternative Resource:

An informative forum thread can be found at this link: [Forum Thread Link]

The above is the detailed content of Can you Preserve Key Order While Sorting Associative Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template