Order multidimensional array recursively at each level in PHP
Use a recursive function:
// Note this method returns a boolean and not the array
function recur_ksort(&$array) {
foreach ($array as &$value) {
if (is_array($value)) recur_ksort($value);
}
return ksort($array);
}
You need to use ksort.
// Not tested ...
function recursive_ksort(&$array) {
foreach ($array as $k => &$v) {
if (is_array($v)) {
recursive_ksort($v);
}
}
return ksort($array);
}
function ksort_recursive(&$array)
{
if (is_array($array)) {
ksort($array);
array_walk($array, 'ksort_recursive');
}
}
As noted in their comments, answers with return ksort()
are incorrect as ksort() returns a success bool.
Note that this function does not throw "Warning: ksort() expects parameter 1 to be array" when given a non-array - this matches my requirements but perhaps not yours.