I've a nested associative array like the one below and need help sorting the array for each of the keys such as 'first_name' and 'score'.
For example:
Array
(
[12345] => Array
(
[75] => Array
(
[first_name] => Xen
[score] => 245
)
)
[9876] => Array
(
[75] => Array
(
[first_name] => Shane
[score] => 300
)
)
[4567] => Array
(
[75] => Array
(
[first_name] => Dan
[score] => 100
)
)
)
The result should have the array sorted by the keys in ascending order:
Array
(
[first_name] => Array
(
[0] => 4567
[1] => 9876
[2] => 12345
)
[score] => Array
(
[0] => 4567
[1] => 12345
[2] => 9876
)
)
ksort
is PHP's function to sort by key. So to sort an array $arr
by its keys, do:
ksort($arr);
Note that ksort
returns a boolean (success or failure), so you shouldn't do $arr = ksort($arr);
. ksort
modifies the original array.
To sort a multidimensional associative array (say, an associative array of associative arrays) recursively by keys, try the user-provided function at the bottom of the ksort
manual page (I haven't tried this, but it looks like it will work just fine):
function deep_ksort(&$arr) {
ksort($arr);
foreach ($arr as &$a) {
if (is_array($a) && !empty($a)) {
deep_ksort($a);
}
}
}