Home  >  Article  >  Backend Development  >  How to use the usort function to custom sort an array in PHP

How to use the usort function to custom sort an array in PHP

王林
王林Original
2023-06-26 12:06:511597browse

When using PHP for array operations, sorting is one of the most common operations. PHP provides many different sorting functions, including the usort function. The usort function can sort an array according to specified rules, but unlike other sorting functions, it allows users to customize the sorting rules.

This article will introduce how to use the usort function in PHP and how to use the usort function for custom sorting.

1. The basic format of the usort function

When using the usort function for sorting, we need to pay attention to the following points:

  • This function requires two parameters, The first parameter is the array that needs to be sorted, and the second parameter is a callback function used to define the sorting rules.
  • The callback function needs to define a rule for comparing the sizes of two elements. Specifically, it needs to return an integer value. The meaning of the return value is:
  • Greater than 0 means that the first element is larger than The second element is larger and needs to be swapped;
  • equals 0 means the two elements are equal and does not need to be swapped;
  • is less than 0 means the first element is smaller than the second element and does not need to be swapped. Need to exchange positions.

Speaking of which, we need to understand the anonymous functions in PHP. An anonymous function is a piece of code that does not have a name and can be defined and stored in a variable.

The following is the basic format of the usort function:

usort(array &$array, callable $cmp_function)

Among them, $array is the array that needs to be sorted, and $cmp_function is the callback function used to define the sorting rules.

2. Examples of using the usort function

Let’s take a look at examples of using the usort function.

<?php
$fruits = array("apple", "banana", "orange", "peach");

function cmp($a, $b)
{
    return strlen($a) - strlen($b);
}

usort($fruits, "cmp");

print_r($fruits);
?>

In the above example, we first defined an array $fruits, which contains four fruits. Next, we define a callback function cmp to implement the rule of sorting string lengths from small to large. In the usort function, we pass the $fruits array and the cmp function as parameters. After the function is executed, the $fruits array will be sorted according to the rules of string length from small to large.

The running results are as follows:

Array
(
    [0] => apple
    [1] => peach
    [2] => banana
    [3] => orange
)

3. Use the usort function for custom sorting

In addition to using the usort function for ordinary sorting, we can also define custom sorting according to our own needs. Define sorting rules.

The following is an example. We use the usort function to sort a two-dimensional array containing people's names and ages in ascending order of age.

<?php
$people = array(
    array('name' => 'Jim', 'age' => 23),
    array('name' => 'Tom', 'age' => 18),
    array('name' => 'Lucy', 'age' => 26),
    array('name' => 'Lily', 'age' => 20),
);

function cmp($a, $b)
{
    return $a['age'] - $b['age'];
}

usort($people, "cmp");

print_r($people);
?>

In the above example, we defined a two-dimensional array $people, which contains two fields: name and age. Next, we define a callback function cmp to implement the rules of sorting by age from small to large. What is returned in the function is $a['age'] - $b['age'], which means that the array is sorted from small to large by age.

The running results are as follows:

Array
(
    [0] => Array
        (
            [name] => Tom
            [age] => 18
        )

    [1] => Array
        (
            [name] => Lily
            [age] => 20
        )

    [2] => Array
        (
            [name] => Jim
            [age] => 23
        )

    [3] => Array
        (
            [name] => Lucy
            [age] => 26
        )

)

You can see that according to the rules we defined, the $people array has been sorted from small to large by age.

Through the above example, we can find that the usort function has very powerful custom sorting capabilities. Different sorting rules can be implemented by simply defining a callback function. But it should be noted that the callback function needs to return an integer value to ensure that the function can work properly.

The above is the detailed content of How to use the usort function to custom sort an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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