Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Sorting Nested Associative Arrays

foreach ($a as $key => $value) {
  if (is_array($value)) {
    sortNestedArrayAssoc($value);
  }
}
<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>

Sorting an Associative Nested Array Using a Recursive Function (sortNestedArrayAssoc.php)

If an associative nested array is to be sorted, two things have to be changed in comparison to the previous phrase that sorted a numeric (but nested) array. First, the array has to be sorted using ksort(), not sort(). 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:

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

Figure 2.5 shows the result of the code at the beginning of this phrase.

Figure 2.5

Figure 2.5. Sorting nested, associative arrays

  • + Share This
  • 🔖 Save To Your Account