Home > Backend Development > PHP Tutorial > Advanced sorting of PHP arrays: custom comparators and anonymous functions

Advanced sorting of PHP arrays: custom comparators and anonymous functions

王林
Release: 2024-04-27 11:09:02
Original
703 people have browsed it

In PHP, there are two ways to sort an array in a custom order: Custom comparator: implement the Comparable interface and specify the comparison rules of the two objects. Anonymous function: Create an anonymous function as a custom comparator to compare two objects against a criterion.

PHP 数组高级排序:自定义比较器和 匿名函数

PHP Array Advanced Sorting: Custom Comparator and Anonymous Function

In PHP, sort arrays in custom order Sorting requires functionality beyond what the standard sort functions can provide. Custom comparators and anonymous functions provide a more flexible sorting mechanism than built-in functions such as sort() and rsort().

Custom comparator

A custom comparator is a class that implements the Comparable interface, which defines how to compare two objects. Implement the compareTo() method to specify which object is considered greater than, less than, or equal to another object.

class CustomComparator implements Comparable {
    public function compareTo($a, $b): int {
        if ($a == $b) {
            return 0;
        }
        return $a > $b ? 1 : -1;
    }
}
Copy after login

Anonymous functions

Anonymous functions are unnamed functions that can be created on the fly and passed as arguments. They are often used to create custom comparators:

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

Practical example

Consider an array containing student names and scores:

$students = [
    ['name' => 'Alice', 'score' => 85],
    ['name' => 'Bob', 'score' => 90],
    ['name' => 'Carol', 'score' => 80],
];
Copy after login

Custom comparator method

$comparator = new CustomComparator();
usort($students, [$comparator, 'compareTo']);
Copy after login

Anonymous function method

usort($students, function($a, $b) {
    return $a['score'] <=> $b['score'];
});
Copy after login

The above code will sort the array from small to large student scores:

[
    ['name' => 'Carol', 'score' => 80],
    ['name' => 'Alice', 'score' => 85],
    ['name' => 'Bob', 'score' => 90],
];
Copy after login

The above is the detailed content of Advanced sorting of PHP arrays: custom comparators and anonymous functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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