Hello Everyone,
I have an date array in m-d-y format and I want to sort this in (ASC/DESC) order.
I have done this by converting date to "timestamps" and then sorted.
What is the best way ??
Sorting the date array
Moderator: General Moderators
- Frozenlight777
- Forum Commoner
- Posts: 75
- Joined: Wed May 28, 2008 12:59 pm
Re: Sorting the date array
Have you tried to use the sort function? Not sure if will sort the dates but you can give this a shot.
modify the 8 to whatever it needs to be
Code: Select all
<?php
sort($datearray);
for($i=0; $i<8; $i++)
{
print $datearray[$i] . "<br />";
}
?>-
madan koshti
- Forum Commoner
- Posts: 50
- Joined: Fri Jun 06, 2008 4:25 am
Re: Sorting the date array
Hi,
This will never do my task!
This will never do my task!
Re: Sorting the date array
The best solution would be to sort them at the database level if you can, otherwise you can simply change the format to YY-MM-DD and use the standard array sorting options.
But I was bored so I wrote this for you. It's untested.
But I was bored so I wrote this for you. It's untested.
Code: Select all
function lpad($var, $int)
{
return (string) str_pad($var, $int, "0", STR_PAD_LEFT);
}
function datesort_asc($array_dates){
$compare = create_function('$a,$b','
$a = explode("-", $a);
$b = explode("-", $b);
if ((lpad($a[2], 4) . lpad($a[0], 2) . lpad($a[1])) == (lpad($b[2], 4) . lpad($b[0], 2) . lpad($b[1])))
{
return 0;
} else {
return ((lpad($a[2], 4) . lpad($a[0], 2) . lpad($a[1])) > (lpad($b[2], 4) . lpad($b[0], 2) . lpad($b[1]))) ? -1 : 1;
}
');
usort($array_dates,$compare);
return $array_dates;
}
function datesort_desc($array_dates){
$compare = create_function('$a,$b','
$a = explode("-", $a);
$b = explode("-", $b);
if ((lpad($a[2], 4) . lpad($a[0], 2) . lpad($a[1])) == (lpad($b[2], 4) . lpad($b[0], 2) . lpad($b[1])))
{
return 0;
} else {
return ((lpad($a[2], 4) . lpad($a[0], 2) . lpad($a[1])) > (lpad($b[2], 4) . lpad($b[0], 2) . lpad($b[1]))) ? 1 : -1;
}
');
usort($array_dates,$compare);
return $array_dates;
}
-
madan koshti
- Forum Commoner
- Posts: 50
- Joined: Fri Jun 06, 2008 4:25 am
Re: Sorting the date array
hey
Thanks for reply .
Thanks for reply .