PHP

Sorting Nested Associative Arrays

If an associative nested array is to be sorted, two things have to be changed in comparison to the previous coding that sorted a numeric (but nested) array. First, the array has to be sorted using ksort(), not sort().

foreach ($a as $key => $value) {
  if (is_array($value)) {
    sortNestedArrayAssoc($value);
  }
}

Furthermore, the recursive sorting has to be applied to the right variable, the array element that itself is an array. Make sure that this is passed via reference, so that the changes are applied back to the value.

Sorting a Nested Associative Array Using a Recursive Function

<pre>
<?php
  function sortNestedArrayAssoc($a) {
    ksort($a);
    foreach ($a as $key => $value) {
      if (is_array($value)) {
        sortNestedArrayAssoc($value);
      }
    }
  }
  $arr = array(
    'Roman' =>
      array('one' => 'I', 'two' => 'II', 'three' =>
        'III', 'four' => 'IV'),
    'Arabic' =>
      array('one' => '1', 'two' => '2', 'three' =>
        '3', 'four' => '4')
  );
  sortNestedArrayAssoc(&$arr);
  print_r($arr);
?>
</pre>

Figure shows the result of the code at the beginning of This.

Sorting nested, associative arrays.

by BrainBellupdated
Advertisement: