"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-08
Browse:144

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'] 

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].

Release Statement This article is reprinted at: 1729422320 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3