Home > Backend Development > PHP Tutorial > How Can I Sort a Multi-Dimensional Array in PHP Using `usort()` and `uasort()`?

How Can I Sort a Multi-Dimensional Array in PHP Using `usort()` and `uasort()`?

Susan Sarandon
Release: 2024-12-27 03:41:09
Original
523 people have browsed it

How Can I Sort a Multi-Dimensional Array in PHP Using `usort()` and `uasort()`?

Sorting a Multi-Dimensional Array by Value

Many situations arise when the need to sort a multi-dimensional array is necessary. This can be achieved with the use of a user-defined comparison function within the usort() function.

Sorting by a Single Key Using usort()

To sort the given array by the value of the "order" key, we can define a sorting function as follows:

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

usort($myArray, 'sortByOrder');
Copy after login

Alternatively, we can 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;
});
Copy after login

Multi-Dimensional Sorting

This approach can be extended to sort multi-dimensional arrays. For instance, to sort by "order" and then "suborder":

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

Preserving Key Associations with uasort()

If you need to retain key associations, use uasort(). For comparison, refer to the manual's comparison of array sorting functions.

The above is the detailed content of How Can I Sort a Multi-Dimensional Array in PHP Using `usort()` and `uasort()`?. 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