Sorting the date array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
madan koshti
Forum Commoner
Posts: 50
Joined: Fri Jun 06, 2008 4:25 am

Sorting the date array

Post 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 ??
User avatar
Frozenlight777
Forum Commoner
Posts: 75
Joined: Wed May 28, 2008 12:59 pm

Re: Sorting the date array

Post 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
madan koshti
Forum Commoner
Posts: 50
Joined: Fri Jun 06, 2008 4:25 am

Re: Sorting the date array

Post by madan koshti »

Hi,

This will never do my task!
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Sorting the date array

Post 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;
}
 
madan koshti
Forum Commoner
Posts: 50
Joined: Fri Jun 06, 2008 4:25 am

Re: Sorting the date array

Post by madan koshti »

hey

Thanks for reply . :)
Post Reply