"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 Custom Sort Multidimensional Arrays Based on a Specific Key in PHP?

How to Custom Sort Multidimensional Arrays Based on a Specific Key in PHP?

Published on 2024-11-08
Browse:582

How to Custom Sort Multidimensional Arrays Based on a Specific Key in PHP?

Custom Sorting of Multidimensional Arrays

Sorting multidimensional arrays can be a common task in programming. This article demonstrates how to sort such an array based on a specific key using the PHP usort() function.

Understanding the Task

Consider the following multidimensional array where each element represents a record:

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
        ))

Sorting by a Key

To sort this array by the "status" key, we need to define a comparison function that determines the order of the elements.

function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] 

This function compares the "status" values of two elements. If the values are equal, it returns 0. If the first element has a lower "status" value than the second, it returns -1. Otherwise, it returns 1.

Using usort()

We can now use the usort() function to sort the array using our comparison function:

usort($array, "cmp");

This will sort the array in ascending order based on the "status" key. The modified array will have its elements rearranged accordingly.

Customizing the Comparison

The comparison function can be customized to sort the array based on any key. Simply modify the function to compare the desired key values. This provides flexibility in sorting multidimensional arrays based on different criteria.

Release Statement This article is reprinted at: 1729422140 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