phparrayssortingmultidimensional-array

Sorting a multidimensional array by column value


I've an array like this

Array
(

[0] => Array

        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ABC
                            [id] => 123232
                            [name] => Apple

                        )

                    [1] => Array
                        (
                            [type] => DEF
                            [id] => 2323232
                            [name] => Banana

                        )

                )


            [title] => Cool
            [rank] => 2
        )

  [1] => Array
        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ZX
                            [id] => 3223
                            [name] => Danny

                        )

                    [1] => Array
                        (
                            [type] => QWER
                            [id] => 2323232
                            [name] => Cactus

                        )

                )


            [title] => Hot
            [rank] => 1
        )


[3]..
[4]..and son on

I would like to sort by rank, is there any quick sort method in PHP to do that?


Solution

  • You can use the usort function:

    function cmp($a, $b) {
        return $a['rank'] - $b['rank'];
    }
    
    $arr = /* your array */
    
    usort($arr, "cmp");
    

    See it

    To sort on rank in descending order (question asked in comments), you just reverse the order in the compare function:

    function cmp($a, $b) {
        return $b['rank'] - $a['rank'];
               ^^           ^^
    }