Sort array by date...

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
jkashu
Forum Commoner
Posts: 45
Joined: Tue Jan 30, 2007 12:00 pm

Sort array by date...

Post by jkashu »

I read a list of dates from a text into array. Now I need to sort the array by dates. The format is this: 7 Apr 2008, 10:22 am

Seems to me, if I can switch it to this format 2008 04 07, then I can sort it numerically. Is this right? If so, how do I change the format??

Thanks!
JacobT
Forum Commoner
Posts: 43
Joined: Tue May 13, 2008 11:07 am
Location: Los Angeles, CA

Re: Sort array by date...

Post by JacobT »

hey jkashu, here's what I would do:

You can convert pretty much any date string into a unix timestamp (number of seconds since the epoch) using the function strtotime($string); It's a wonderful function that works amazingly for this type of situation.

By turning your array keys into seconds, they will always be sortable. You can sort them normally using the ksort() function or sort them in reverse using the krsort() function.

I hope this helps! Good luck with your coding!

Here's a snippet of code that works so you can see a functional example:

Code: Select all

<?php
    $yourArray = array('12 Apr 2008, 10:22 am','15 Apr 2008, 08:22 am','7 Apr 2008, 10:22 am');
    
    foreach($yourArray as $date) {
        $unixTime = strtotime($date);
        $newArray[$unixTime] = $date;
    }
    
    ksort($newArray);
    
    foreach($newArray as $key => $value) {
        echo $value, '<br />';
    }
    
    /* Outputs
     * 7 Apr 2008, 10:22 am
     * 12 Apr 2008, 10:22 am
     * 15 Apr 2008, 08:22 am
    */
?>
jkashu
Forum Commoner
Posts: 45
Joined: Tue Jan 30, 2007 12:00 pm

Re: Sort array by date...

Post by jkashu »

This snippet of code only gives me one date as output... I have been messing strtotime() , etc. for awhile to no avail.

Output:

7 Apr 2008, 10:22 am
jkashu
Forum Commoner
Posts: 45
Joined: Tue Jan 30, 2007 12:00 pm

Re: Sort array by date...

Post by jkashu »

Ok...now I'm confused. I ran the code on a godaddy server and another server that I have (hosted through AFMU.com). The godaddy one only gives me one date, but the other server works fine.

If I print the keys of the array, for godaddy get:

output:

-1

for the other one:

output:

1207578120
1208010120
1208262120
JacobT
Forum Commoner
Posts: 43
Joined: Tue May 13, 2008 11:07 am
Location: Los Angeles, CA

Re: Sort array by date...

Post by JacobT »

Sorry mate, I can't help with GoDaddy problems, I've never hosted with them and I'm not fluent in the WinX differences if that's what the server is.

Good luck, I hope someone with more experience can help you out.
Post Reply