Sorting Nested Associative Arrays


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


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.

Sorting a Nested Associative Array Using a Recursive Function (sortNestedArrayAssoc.php)
 <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 2.5 shows the result of the code at the beginning of this phrase.

Figure 2.5. Sorting nested, associative arrays.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net