Page 1 of 1

Sorting the date array

Posted: Mon Jun 09, 2008 7:29 am
by madan koshti
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 ??

Re: Sorting the date array

Posted: Mon Jun 09, 2008 8:52 am
by Frozenlight777
Have you tried to use the sort function? Not sure if will sort the dates but you can give this a shot.

Code: Select all

<?php
 
sort($datearray);
for($i=0; $i<8; $i++)
  {
         print $datearray[$i] . "<br />";
  }
 
?>
modify the 8 to whatever it needs to be

Re: Sorting the date array

Posted: Tue Jun 10, 2008 1:47 am
by madan koshti
Hi,

This will never do my task!

Re: Sorting the date array

Posted: Tue Jun 10, 2008 1:48 am
by Benjamin
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.

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

Re: Sorting the date array

Posted: Tue Jun 10, 2008 2:43 am
by madan koshti
hey

Thanks for reply . :)