简体   繁体   English

如何从mysql到php排序月份

[英]How to sort month years from mysql to php

I have a list from mysql db which includes months combined with years that need to be sorted accordingly. 我有一个来自mysql db的列表,其中包括月份和需要相应排序的年份。 At the moment the returned list (ordered DESC) looks like this: 目前,返回的列表(排序为DESC)如下所示:

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 我希望上面的列表遵循逻辑排序,其中2016年1月位于列表的顶部,例如

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? 我该如何在php中实现呢?

*Update the sql query I used is: *更新我使用的SQL查询是:

SELECT mnthyears FROM dates ORDER BY mnthyears DESC

Using mysql LPAD (padding function) combined with SUBSTR method in ORDER BY clause: 在ORDER BY子句中将mysql LPAD(填充函数)与SUBSTR方法结合使用:

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 但是,如果只有5或6位数字的字符串(不带“ - (Dec 2015) ”)),只需将19更改为6

use MySQL str_to_date 使用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 考虑到日期字符串更改的长度 ,您应该可以在SQL代码中实现此目的-以后无需在PHP中完成此操作

select case when len(mnthyears ) = 18 then '0'+mnthyears else date_column end 
   as mnthyears FROM dates ORDER BY 1 DESC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM