"Simple" sort a nested array using array_multisort or native PHP functions instead of my own foreach loop
- by Ana Ban
I have the following array of days of the week, with each day having hours of the day (the whole array represents the schedule of a part-time employee):
Array
(
[7] => Array
(
[0] => 15
[1] => 14
[2] => 13
[3] => 11
[4] => 12
[5] => 10
)
[1] => Array
(
[0] => 10
[1] => 13
[2] => 12
)
[6] => Array
(
[0] => 14
)
[3] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
)
and I simply need to:
sort asc each sub-array (2nd dimension) - no need to maintain the numeric keys, values are integers
sort asc the 1st dimension and maintain the numeric, integer keys
ie:
Array
(
[1] => Array
(
[0] => 10
[1] => 12
[2] => 13
)
[3] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[6] => Array
(
[0] => 14
)
[7] => Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
)
)
Additional info:
only the keys of the 1st dimension and the values of the 2nd dimension (and of course their association) are meaningful to my use-case
the 1st dimension can have at most 7 values, ranging from 1-7 (days of the week), and will have at least 1 value (1 day)
the 2nd dimension can have at most 24 values, ranging from 0-23 (hours of each day), and will have at least 1 value (1 hour per day)
I know I can do this with a foreach on the whole ksorted array and sort each 2nd dimension array:
ksort($sched);
foreach ($sched as &$array) sort($array);
unset($array);
but I was hoping I could achieve this with native php array function(s) instead.
My search led me to try array_multisort(array_values($array), array_keys($array), $array) but I just can't make it work.