Home  >  Article  >  Backend Development  >  How to Sort Multidimensional Arrays by a Specific Key Using usort and Custom Comparison Function?

How to Sort Multidimensional Arrays by a Specific Key Using usort and Custom Comparison Function?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 19:07:02476browse

How to Sort Multidimensional Arrays by a Specific Key Using usort and Custom Comparison Function?

Sorting Multidimensional Arrays by Key

A common task when working with multidimensional arrays is the need to sort them according to a specific key. For instance, consider the following array:

Array (
[0] => Array
    (
        [iid] => 1
        [invitee] => 174
        [nid] => 324343
        [showtime] => 2010-05-09 15:15:00
        [location] => 13
        [status] => 1
        [created] => 2010-05-09 15:05:00
        [updated] => 2010-05-09 16:24:00
    )

[1] => Array
    (
        [iid] => 1
        [invitee] => 220
        [nid] => 21232
        [showtime] => 2010-05-09 15:15:00
        [location] => 12
        [status] => 0
        [created] => 2010-05-10 18:11:00
        [updated] => 2010-05-10 18:11:00
    ))

To sort this array by the [status] key, you can use the usort function along with a custom comparison function:

// Define a comparison function
function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] < $b['status']) ? -1 : 1;
}

// Sort the array using the custom comparison function
usort($array, "cmp");

By defining the cmp function, you specify how elements should be compared during sorting. In this case, it compares the [status] key of the two elements, returning -1 if $a['status'] is less than $b['status'], 0 if they are equal, and 1 otherwise.

The usort function arranges the array elements in ascending order based on the comparison function's output. This allows you to sort the multidimensional array by the desired key, in this case, [status].

The above is the detailed content of How to Sort Multidimensional Arrays by a Specific Key Using usort and Custom Comparison Function?. 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