RE: [PHP] Sort Array by date
| From: | Martin Towell | Date: | Thu, 04 Dec 2003 22:26:00 +0000 |
| Subject: | RE: [PHP] Sort Array by date | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-171907@lists.php.net to get a copy of this message | ||
Hiya,
I changed your date_file_sort() function so it echos a few things
function date_file_sort($a, $b)
{
echo "$a - $b - ";
$a = strtotime($a);
$b = strtotime($b);
echo "$a - $b - ".date("d-M-Y", $a)." - ".date("d-M-Y",
$b)."\n";
return strcmp($a, $b);
}
"interesting" results....
Here's an alterative to this function that works (might not be the best way
though??)
function date_file_sort($a, $b)
{
list($x, $y, $z) = explode("-", $a); $a = "$z-$y-$x";
list($x, $y, $z) = explode("-", $b); $b = "$z-$y-$x";
return -strcmp($a, $b);
}
HTH
Martin
>
> 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?
>
> $menu_item = array();
> $menu_item[] = "12-04-2003";
> $menu_item[] = "11-19-2003";
> $menu_item[] = "01-04-2004";
> $menu_item[] = "12-24-2003";
> $menu_item[] = "08-13-1982";
>
> // sorting function
> function date_file_sort($a, $b)
> {
> $a = strtotime($a);
> $b = strtotime($b);
> return strcmp($a, $b);
> }
>
> usort($menu_item, 'date_file_sort');
>
> // output results
> for($x = 0; $x < count($menu_item); $x++)
> {
> echo $menu_item[$x]."<br>";
> }
>
>
> Here are the the results I get:
> 01-04-2004
> 08-13-1982
> 12-04-2003
> 11-19-2003
> 12-24-2003
> Anyone know why these results seem totally random? Please help.
>
> Thanks,
>
> Matt