- Accessing All Elements of Numeric Arrays
- Accessing All Elements of Associative Arrays
- Accessing All Array Elements in Nested Arrays
- Turning an Array into Variables
- Converting Strings to Arrays
- Converting Arrays to Strings
- Sorting Arrays Alphabetically
- Sorting Associative Arrays Alphabetically
- Sorting Nested Arrays
- Sorting Nested Associative Arrays
- Sorting IP Addresses (as a Human Would)
- Sorting Anything
- Sorting with Foreign Languages
- Applying an Effect to All Array Elements
- Filtering Arrays
- Getting Random Elements Out of Arrays
- Making Objects Behave Like Arrays
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. Sorting nested, associative arrays