Page 1 of 1
Sort array by date...
Posted: Tue May 13, 2008 5:22 pm
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!
Re: Sort array by date...
Posted: Tue May 13, 2008 5:53 pm
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
*/
?>
Re: Sort array by date...
Posted: Tue May 13, 2008 6:02 pm
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
Re: Sort array by date...
Posted: Tue May 13, 2008 6:11 pm
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
Re: Sort array by date...
Posted: Tue May 13, 2008 6:23 pm
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.