Tuesday 14 August 2018

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-
1
2
3
4
5
6
7
8
9
10
11
<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>
Output:
How it works:
Line 3-7See the keys of the nested arrays are 5, 3, and 7 successively. We’ll sort these keys by ascending order.
Line 9After 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-
1
2
3
4
5
6
7
8
9
10
11
<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>
Output:
How it works:
Line 3-7The keys of the multidimensional array are 5, 3, and 7. We’ll sort these keys descending order.
Line 9After 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.

0 comments:

Post a Comment