I have a list from mysql db which includes months combined with years that need to be sorted accordingly. At the moment the returned list (ordered DESC) looks like this:
122015 - (Dec 2015)
112015 - (Nov 2015)
102015 - (Oct 2015)
92015 - (Sep 2015)
82015 - (Aug 2015)
12016 - (Jan 2016)
I would like the above list to follow logical sorting with Jan 2016 being top of the list eg
12016 - (Jan 2016)
122015 - (Dec 2015)
112015 - (Nov 2015)
102015 - (Oct 2015)
92015 - (Sep 2015)
82015 - (Aug 2015)
How do I go about achieving this in php?
*Update the sql query I used is:
SELECT mnthyears FROM dates ORDER BY mnthyears DESC
Using mysql LPAD (padding function) combined with SUBSTR method in ORDER BY clause:
SELECT mnthyears
FROM dates
ORDER BY SUBSTR(LPAD( mnthyears, 19, '0'),3,4) DESC, SUBSTR(LPAD(mnthyears,19,'0'),1,2) DESC
If however you have only those 5 or 6 digits strings (without " - (Dec 2015)
"), just change 19 to 6
use MySQL str_to_date
str_to_date(replace(replace('(Jan 2016)',')',''),'(',''),'%b %Y')
Query
SELECT mnthyears FROM dates
ORDER BY str_to_date(replace(replace('(Jan 2016)',')',''),'(',''),'%b %Y') DESC
Considering the length of your date string changes, you should be able to pull this off inside your SQL code - no need to do it in PHP afterwards
select case when len(mnthyears ) = 18 then '0'+mnthyears else date_column end
as mnthyears FROM dates ORDER BY 1 DESC;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.