PHP按日期排序 [英] PHP sorting by date

查看:395
本文介绍了PHP按日期排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用usort,但是出现问题

I have tried to use usort but I am having issues

我现在已经使用了usort函数.

I have now used the usort function.

我的数组有一个字符串键和一个代表日期的字符串值

my array is has a string key and a string value which represents the date

我的输出如下:

02/09/2013
03/09/2013
03/10/2013
04/07/2013
04/09/2013
09/09/2013
11/09/2013
13/06/2013
13/08/2013

它只按前两个数字排序,我希望它按完整日期排序,我在做什么错了?

It is only sorting by the first two numbers, I want it to sort for the full date, What am I doing wrong?

这是我的代码:

usort($filesWithDates,"my_sort");
foreach ($filesWithDates as &$value) {
    echo $value."<br/>";
}

function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
foreach ($filesWithDates as &$value) {
        echo $value."<br/>";
    }

推荐答案

这些不是日期.这些是字符串.您需要将日期设置为适当的格式,该格式可以按字符串排序,也可以使用DateTime()将它们作为日期进行比较:

Those aren't dates. Those are strings. You need to put your dates into a proper format that is either sortable as strings or compare them as dates using DateTime():

usort($filesWithDates, function($a, $b) {
    $date1 = DateTime::createFromFormat('d/m/Y', $a);
    $date2 = DateTime::createFromFormat('d/m/Y', $b);
    return $date1 > $date2;
});
foreach ($filesWithDates as $value) {
    echo $value."<br/>";
}

这篇关于PHP按日期排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆