- 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 Arrays
function sortNestedArray(&$a) { sort($a); for ($i = 0; $i < count($a); $i++) { if (is_array($a[$i])) { sortNestedArray($a[$i]); } } }
<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>
Sorting a Nested Array Using a Recursive Function (sortNestedArray.php)
The standard sorting functions of PHP do not traverse nested arrays when performing their operations. However, if you use a recursive function, you can code this in just a few lines.
The goal is to sort an array that is nested but consists only of numeric subarrays so that only numeric (and, therefore, useless) keys are used.
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 2.4 shows the result for a sample array.
Figure 2.4. Sorting nested arrays