Reputation: 1008
I'm making an event calendar. Everything needs to be sorted chronologically.
This is the array I'm currently sorting:
$years = array(
2018 => array(
01 => array(),
02 => array()
),
2017 => array(,
02 => array()
01 => array()
)
);
I originally have a larger array used to populate this $years
.
Using ksort
, I've sorted my years
correctly, i.e. they are in chronological order. However, I can't sort my third level (see in 2017
, my array is 02,01
whereas it should read 01,02
). The last level or the array (such as 2017 > 02
) is sorted correctly, this is not an issue, as these are sorted by content within each of them.
I've tried array_multisort
, ksort
, usort
and simply sort
but none allow me to sort my keys as they are numeric.
Upvotes: 1
Views: 422
Reputation: 15141
Hope this one will be helpful. Here we are using ksort
for sorting array on the basis of keys.
ksort($years);
$result=array_map(
function($array) {
ksort($array);
return $array;
},
$years);
Upvotes: 2
Reputation: 9927
How about iterating through the children elements, sorting them with ksort()
as well:
<?php
$years = array(
2018 => array(
01 => array(),
02 => array()
),
2017 => array(
02 => array(),
01 => array()
)
);
ksort($years);
foreach ($years as &$year) {
ksort($year);
}
var_dump($years);
Upvotes: 3