Can PHP\'s built-in sorting functions preserve key order when sorting associative arrays with equal values?

Mary-Kate Olsen
Release: 2024-11-04 07:14:30
Original
676 people have browsed it

Can PHP's built-in sorting functions preserve key order when sorting associative arrays with equal values?

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>
Copy after login

By using this function, you can sort your associative array while maintaining the original key order for elements with equal values.

Additional Resources:

  • PHP Stable Sort Forum Thread

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!