Categories
PHP

Sorting Nested Arrays

PHP sorting functions can not perform a deep sort on nested arrays. To solve this problem, create a recursive function that calls any PHP sorting function and sorts a nested array deeply (by calling a sorting function recursively).

Sorting a nested array by values

<?php
 function deepSort(&$arr, $cb){
  $cb($arr);
  foreach ($arr as $k => $v) {
   if (is_array ($v) ){
    deepSort($arr[$k], $cb);  
   }
  }
 }

The deepSort function has two parameters &$arr and $cb. Make sure the array is passed via reference, so that the changes are applied back to the value, that’s why we used & sign before the $arr parameter to pass the array as reference.

The $cb is a callback function, PHP allows you to pass a function by its name as a string. We used this feature to pass PHP sorting functions as callback functions.

Furthermore, the recursive sorting has to be applied to the right variable, the array element that itself is an array. The is_array function tests the variable and calls the deepSort function for each array element.

Example: Sorting nested array by value

<?php
 function deepSort(&$arr, $cb){
  $cb($arr);
  foreach ($arr as $k => $v) {
   if (is_array ($v) ){
    deepSort($arr[$k], $cb);  
   }
  }
 }
 
 $a = [1,100,2,5,'z', 'd',
       ['x','i', 'xi',
	    ['b','p','c']
       ],'a', 'c',
	   [10, 5, 2]
      ,8,'m'];

 //pass sort function as a string to $cb
 deepSort($a, 'sort'); 

The sort() function does sort the array (using $cb callback function), but leaves out all subarrays. Therefore, for all elements that are arrays, the sorting function is called again, recursively.

In the above example, we used the PHP sort function and pass it as a string, the above example sorts the array in ascending order recursively. To sort a nested array in descending order, pass the rsort function as a string to the deepSort function.

<?php
 deepSort($a, 'rsort');   

The preceding code shows this concept and figure shows the result for a sample array.

PHP nested array sorting using sort and rsort functions.

Sorting a nested associative array by values or keys

Call the deepSort function and pass the array variable and the name of any associative array sorting function as a string, see following example:

<?php
 function deepSort(&$arr, $cb){
  $cb($arr);
  foreach ($arr as $k => $v) {
   if (is_array ($v) ){
    deepSort($arr[$k], $cb);  
   }
  }
 }

 $arr = [
     'a'=>[5,1,3],
     't'=>['z'=>'kk','a'=>'in','s'=>'sa'],
     'c'=>['one'=>1,'three'=>3,'two'=>2]
       ];

 deepSort ($arr, 'asort'); //by value
 print_r($arr);
 deepSort ($arr, 'ksort'); //by key
 print_r($arr);
 deepSort ($arr, 'arsort');//by value desc
 print_r($arr);
 deepSort ($arr, 'krsort');//by key desc
 print_r($arr);

The preceding code the result for a sample array:

PHP nested associative array sorting with asort, ksort, arsort and krsort functions.

More Posts on PHP Sorting Arrays: