I have a multi dimensional array of items which all have a date. The array follows the format: $relatedItems[$year][$month][$day][]
. Is there a way of sorting this so that it is in date order. I've tried krsort()
bu i think that will just sort the year key e.g. [2014]. Sorry if this is vague I'm new to php.
Array
(
[2014] => Array
(
[01] => Array
(
[13] => Array
(
[0] => Array
(
[type] => news-blog
[title] => Jungle News
[date] => 13th January 2014
[url] => /sport/jungle-ultra/news/jungle-news/
[description] => Description goes here
)
)
[23] => Array
(
[0] => Array
(
[type] => gallery
[title] => New Gallery
[url] => /sport/jungle-ultra/galleries/new-gallery/
[images] => Array
(
[0] => Array
(
[title] => 10.jpg
[src] => /files/cache/978f98c61f63757334fbeec79fabe482_f65.jpg
)
[1] => Array
(
[title] => 9.jpg
[src] => /files/cache/1526727d35b28930b49c69b065a229de_f64.jpg
)
[2] => Array
(
[title] => 8.jpg
[src] => /files/cache/d1b67fefed5e7b7644ad9ec1fe8559ae_f63.jpg
)
[3] => Array
(
[title] => 7.jpg
[src] => /files/cache/80160e395233a15d1b1df4df67ec565d_f62.jpg
)
[4] => Array
(
[title] => 6.jpg
[src] => /files/cache/48575e2d53c487f99633a1105e7a322b_f61.jpg
)
[5] => Array
(
[title] => 4.jpg
[src] => /files/cache/9fe01089fc9656562fb7f082499439fc_f60.jpg
)
)
)
)
[27] => Array
(
[0] => Array
(
[type] => video
[title] => Test
[url] => /sport/jungle-ultra/video/test/
[thumb] => /files/5313/8996/9327/speaker-header-small.jpg
)
)
[24] => Array
(
[0] => Array
(
[type] => video
[title] => Rich reaches half way point
[url] => /sport/jungle-ultra/video/rich-reaches-half-way-point/
[thumb] => /files/7013/9039/4602/video-cover-test.jpg
)
)
[21] => Array
(
[0] => Array
(
[type] => audio
[title] => Day 1 - Update from Alexander Island
[url] => /sport/jungle-ultra/audio/day-1-update-alexander-island/
[thumb] => /files/7013/9039/4602/video-cover-test.jpg
)
)
)
)
)
You are correct in using ksort
but you need to use a recursive function. Try using this:
function sort_by_date($dates){
if(is_array($dates)){ // If it is an array
ksort($dates); // Sort the array keys
foreach($dates as $date){ // Loop through the keys
sort_by_date($date); // And call this recursive function on each of the child arrays
}
}
}
Usage:
$array = array(...); // Your date array
sort_by_date($array); // New function for sorting