Jump to content

Archived

This topic is now archived and is closed to further replies.

garry

[SOLVED] Sorting array by date

Recommended Posts

So i have an array with a bunch of arrays inside of it. Of the second arrays, each has a "date" key with a date and time formatted as "24 Oct 2008 05:00:00 AM".

 

What I want to do is to sort this array by date and time, ascending. I've had a look at the array sorting functions on the php.net website and haven't come up with anything i think can do it.. do you guys know any way?

Share this post


Link to post
Share on other sites

Take a look at array_multisort.

 

Note that you'll need to convert "24 Oct 2008 05:00:00 AM" to a PHP timestamp value for your orderBy array

Share this post


Link to post
Share on other sites

Sorry, not my format, it's from an XML feed :(

 

So changing it to a unix timestamp shouldn't be too hard. Once I've done this, which loop would do it? (I had a look at arary_multisort and couldn't see an argument for a key to sort by?)

Share this post


Link to post
Share on other sites

foreach ($dataArray as $key => $row) {
    $orderByDate[$key]  = strtotime($row['date']);
}

array_multisort($orderByDate, SORT_ASC, $dataArray);

Modify as necessary to suit your nested arrays when setting the $orderByDate keys in the loop

Share this post


Link to post
Share on other sites

Worked great, strtotime converted the dates to unix very easily. Thanks both of you :)

Share this post


Link to post
Share on other sites

FYI if your working with dates before "January 1 1970 00:00:00 UTC", use caution with unix timestamps, some computers (older operating systems, solaris) cannot use negative timestamps, since the timestamp of "January 1 1970 00:00:00 UTC" is 0, anythig before that would be -x.

Share this post


Link to post
Share on other sites

Thanks for the note uniflare, all my dates will be recent but that's good to know :)

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.