PHP

Sorting Nested Arrays

The standard sorting functions of PHP have to give up when they work on nested arrays. However, if you use a recursive function, you can code this in just a few lines.

function sortNestedArray(&$a) {
  sort($a);
  for ($i = 0; $i < count($a); $i++) {
    if (is_array($a[$i])) {
      sortNestedArray($a[$i]);
    }
  }
}

The goal is to sort an array that is nested, but consists only of numeric subarrays, so only numeric (and, therefore, useless) keys are used.

Sorting a Nested Array Using a Recursive Function

<pre>
<?php
  function sortNestedArray(&$a) {
    sort($a);
    for ($i = 0; $i < count($a); $i++) {
      if (is_array($a[$i])) {
        sortNestedArray($a[$i]);
      }
    }
  }
  $arr = array(
    'French',
    'Spanish',
    array('British English', 'American English'),
    'Portuguese',
    array('Schwitzerdütsch', 'Deutsch'),
    'Italian'
  );
  sortNestedArray($arr);
  print_r($arr);
?>
</pre>

The idea is the following: Calling sort() does sort the array, but leaves out all subarrays. Therefore, for all elements that are arrays, the sorting function is called again, recursively. The preceding code shows this concept; figure shows the result for a sample array.

Sorting nested arrays.

The PHP function array_multisort() is an alternative way to sort arrays with more than one dimension; however, it has a rather unusual parameter order.

by BrainBellupdated
Advertisement: