How to sort Multi-dimensional Array using one of its parameter(dimension) in PHP?

 

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 5
            [2] => x
        )

    [1] => Array
        (
            [0] => b
            [1] => 3
            [2] => y
        )

    [2] => Array
        (
            [0] => c
            [1] => 8
            [2] => z
        )
)


Using below logic this multidimentional array can be sorted using parameter 1 which is $arr_count.

Code:

$result = array_map(null, $arr_name, $arr_count,$arr_desc);

$keys = array_column($result, '1'); //Here 1 means it will sort basis count, 0 means it will sort based on arr_name, 2 means it will sort based on arr_desc

array_multisort($keys, SORT_DESC, $result);

print_r($result);
Result: 

Array
(
    [0] => Array
        (
            [0] => c
            [1] => 8
            [2] => z
        )

    [1] => Array
        (
            [0] => a
            [1] => 5
            [2] => x
        )

    [2] => Array
        (
            [0] => b
            [1] => 3
            [2] => y
        )
)

 


Related #tags:     #php     #array     #multidimensional-array     #sorting    

Related questions




Looking for change? Click below to prepare for technical interview.


Technical Interview Questions