jarvis Posted March 11, 2021 Share Posted March 11, 2021 Hi, I have a loop which creates an array: $productions[] = array( 'url'=>get_the_permalink(), 'year'=>$production_year->name, 'title'=>get_the_title() ); When I output the results, the year is in the wrong order: 2019 2018 2017 2016 2015 2014 2020 What I can't work out is how to order 2014 - 2020 I tried ksort(array, SORT_STRING) and ksort(array, SORT_NUMERIC) I also tried natsort But still have the same issue - am I missing something? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/312278-sort-array-by-year-gives-wrong-order/ Share on other sites More sharing options...
Solution jarvis Posted March 11, 2021 Author Solution Share Posted March 11, 2021 Sorted it with usort($productions, function($a1, $a2) { $v1 = strtotime($a1['year']); $v2 = strtotime($a2['year']); return $v2 - $v1; // $v2 - $v1 to reverse direction }); Quote Link to comment https://forums.phpfreaks.com/topic/312278-sort-array-by-year-gives-wrong-order/#findComment-1585023 Share on other sites More sharing options...
Barand Posted March 11, 2021 Share Posted March 11, 2021 FYI, as of php7, you could write it as usort($productions, function($a1, $a2) { return $a2['year'] <=> $a1['year']; }); Quote Link to comment https://forums.phpfreaks.com/topic/312278-sort-array-by-year-gives-wrong-order/#findComment-1585024 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.