How do you sort data by date in the form month/day/year (xx/xx/xxxx). Right now I've got my data sorted by Date Desc. So it would go, for example....
05/21/2002
05/14/2002
02/12/2002
But now lets say we throw in the date 07/24/1999. Since PHP sorts by the month and day first 07/24/1999 would go up top instead of on the bottom. Does anyone know how remedy this situation?
Order By
Moderator: General Moderators
Try the usort() function:
If any dates are invalid, add this:
Code: Select all
<?php
$dates = array(
'05/21/2002',
'05/14/2002',
'02/12/2002',
'07/24/1999',
);
usort($dates, "sort_date");
function sort_date($a, $b)
{
// The "Regular Expression" for preg_match():
$re = '(ї0-9]ї0-9])\/'.
'(ї0-9]ї0-9])\/'.
'(ї0-9]ї0-9]ї0-9]ї0-9])';
// Get month, day, year of $a and $b:
preg_match("/$re/", $a, $a_date);
preg_match("/$re/", $b, $b_date);
// $X_date now has 1=month, 2=day, 3=year
// Compare both yyyy/mm/dd strings:
return strcmp(
"$a_dateї3]/$a_dateї1]/$a_dateї2]",
"$b_dateї3]/$b_dateї1]/$b_dateї2]");
}
print_r($dates);
?>Code: Select all
// Get month, day, year of $a and $b:
$a_is_date = preg_match($re, $a, $a_date);
$b_is_date = preg_match($re, $b, $b_date);
if (!$a_is_date || !$b_is_date)
{
if (!$a_is_date && !$b_is_date)
return strcmp($a, $b);
if (!$a_is_date) return -1;
if (!$b_is_date) return 1;
}- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK