Home >Backend Development >PHP Tutorial >How to Sort a Multi-dimensional Array by Value in PHP?

How to Sort a Multi-dimensional Array by Value in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 12:21:11889browse

How to Sort a Multi-dimensional Array by Value in PHP?

Sorting a Multi-dimensional Array by Value

In a multi-dimensional array, you may encounter the need to sort its elements based on the value of a specific key. For instance, consider the following array:

Array
(
    [0] => Array
        (
            [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
            [title] => Flower
            [order] => 3
        )

    [1] => Array
        (
            [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
            [title] => Free
            [order] => 2
        )

    [2] => Array
        (
            [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
            [title] => Ready
            [order] => 1
        )
)

Sorting by the "order" Key

To sort the array by the "order" key, you can employ the usort() function. Here's a comprehensive breakdown of its usage:

PHP 5.2 or Earlier:

Define a sorting function first:

function sortByOrder($a, $b) {
    if ($a['order'] > $b['order']) {
        return 1;
    } elseif ($a['order'] < $b['order']) {
        return -1;
    }
    return 0;
}

PHP 5.3 and Later:

Use an anonymous function:

usort($myArray, function($a, $b) {
    if ($a['order'] > $b['order']) {
        return 1;
    } elseif ($a['order'] < $b['order']) {
        return -1;
    }
    return 0;
});

PHP 7:

Utilize the spaceship operator:

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});

PHP 7.4:

Employ an arrow function:

usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);

Multi-dimensional Sorting:

For multi-dimensional sorting, modify the sorting function to reference subsequent sorting elements if the first element is zero. For instance:

usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

Key Associations

If you need to maintain key associations, use uasort() instead of usort().

The above is the detailed content of How to Sort a Multi-dimensional Array by Value 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