Re: Sort Array by date
| From: | Al | Date: | Fri, 05 Dec 2003 02:47:33 +0000 |
| Subject: | Re: Sort Array by date | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-171937@lists.php.net to get a copy of this message | ||
> I have a bunch of dates in the form: MM-DD-YYYY in an array and I want to
> sort them and display them in descending order. I have tried the usort()
> function below and it's not working. Can anyone help me out here?
Your sorting function uses strtotime, which doesn't recognise data in the
MM-DD-YYYY fomat.
Generally speaking, dates are best stored in the ISO standard format
YYYY-MM-DD so that they can be sorted easily with functions like strcmp.
This format is also recognised by strtotime( ). Look in the code below to
learn how to convert your date format to the ISO standard.
If you can't change the date format, you can also modify your sorting
function as following:
// Note this is untested pseudo-code:
function date_file_sort($a, $b)
{
list ($aMonth, $aDay, $aYear) = explode('-', $a);
$aIsoDate = sprintf("%04d-%02d-%02d", $aYear, $aMonth, $aDay);
list ($bMonth, $bDay, $bYear) = explode('-', $b);
$bIsoDate = sprintf("%04d-%02d-%02d", $bYear, $bMonth, $bDay);
return strcmp($aIsoDate, $bIsoDate);
}
Good luck with it,
Al