PHP sorting by date

2019-07-21 22:46发布

问题:

I have tried to use usort but I am having issues

I have now used the usort function.

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

my output is as follows:

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?

This is my code:

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/>";
    }

回答1:

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/>";
}


回答2:

Convert your dates to integers first:

$datesAsInts = array();
foreach($filesWithDats as $value) {
    $datesAsInts[] = strtotime($value);
}
usort($datesAsInts,"my_sort");
foreach ($datesAsInts as $value) {
    echo date('d/m/Y', $value)."<br/>";
}

function my_sort($a,$b)
{
    if ($a==$b) return 0;
    return ($a<$b)?-1:1;
}