PHP array stable sorting: maintaining the order of equal elements

WBOY
Release: 2024-04-26 15:15:01
Original
461 people have browsed it

Stable sorting of PHP arrays can be achieved by: creating a custom comparator that considers the original index when comparing; using the uasort() function to sort the values ​​according to the key and setting the value to the element containing the original index; These methods ensure that equal elements are sorted in the same order as their original order.

PHP 数组稳定排序:保持相等元素的顺序

PHP array stable sorting: maintaining the order of equal elements

Introduction

Stable sorting ensures that the sorted order of equal elements is the same as the original order. For stable sorting, the following comparisons are valid:

a == b => sort(a) <= sort(b)
Copy after login

The PHP array native sort() and rsort() functions are unstable. This article will explore methods for stable sorting.

Method

1. Custom comparator

Use a custom comparator to compare elements when they are equal Original index:

function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return $a < $b ? -1 : 1;
}
Copy after login

Then use it in the usort() or uksort() function:

usort($arr, 'cmp');
Copy after login

2. Use uasort()

uasort() Sorts values ​​based on keys, ksort() sorts keys. So you can set the value in the array to an element containing the original index and then sort the keys: The scores are sorted while maintaining the original order of students with the same score:

$indices = array_keys($arr);
uasort($arr, function($a, $b) use ($indices) {
    if ($a == $b) {
        return 0;
    }
    return $indices[array_search($a, $arr)] < $indices[array_search($b, $arr)] ? -1 : 1;
});
Copy after login

Output:

$scores = [
    'John' => 90,
    'Mary' => 85,
    'Bob' => 85,
    'Alice' => 95
];

uasort($scores, function($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return $a < $b ? -1 : 1;
});

print_r($scores);
Copy after login
Conclusion

The methods listed above can be implemented in PHP Stable ordering of arrays so that the order of equal elements is maintained.

The above is the detailed content of PHP array stable sorting: maintaining the order of equal elements. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template