How to Sort a Multidimensional Array by Keys in PHP?

Problem:

You have a multidimensional array. You want to sort the array by keys.

Solution:

You can sort a multidimensional array in few ways-

Method 1: Using ksort() function

You can use ksort() function to sort the nested arrays in ascending order. See the following example-

<pre>
<?php
$employees = array(
                    5 => array("Name" => "Peter", "Age" => 27),
                    3 => array("Name" => "Smith", "Age" => 30),
                    7 => array("Name" => "Jack", "Age" => 42)
            );

if(ksort($employees))  print_r($employees);
?>
</pre>
</pre>

[wpdm_file id=100]

Output:

Array(   
    [3] => Array       
        (           
            [Name] => Smith           
            [Age] => 30       
        )    
    [5] => Array       
        (           
            [Name] => Peter           
            [Age] => 27       
         )    
     [7] => Array       
         (           
            [Name] => Jack           
            [Age] => 42       
         ) 
)

How it works:

Line 3-7 See the keys of the nested arrays are 5, 3, and 7 successively. We’ll sort these keys by ascending order.
Line 9 After successfully sorting the array $employees[] by keys, ksort() function returns true, and prints the sorted array. See that the keys are now sorted in ascending order as 3, 5, and 7.

 

Method 2: Using krsort() function

You can also use krsort() function to sort the keys of the multidimensional array. The difference between the previous function with one is that krsort() function will sort keys in reverse order. See the following example-

<pre>
<?php
$employees = array(
            5 => array("Name" => "Peter", "Age" => 27),
            3 => array("Name" => "Smith", "Age" => 30),
            7 => array("Name" => "Jack", "Age" => 42)
            );

if(krsort($employees))  print_r($employees);
?>
</pre>

[wpdm_file id=101]

Output:

Array(
     [7] => Array
             (
             [Name] => Jack
             [Age] => 42
             )
     [5] => Array
             (
             [Name] => Peter
             [Age] => 27
             )
     [3] => Array
             (
             [Name] => Smith
             [Age] => 30
             )
)

How it works:

Line 3-7 The keys of the multidimensional array are 5, 3, and 7. We’ll sort these keys descending order.
Line 9 After successful sorting the array $employees[] by keys, krsort() function returns true and prints the sorted array. See that the keys are now sorted in descending order as 7, 5, and 3.