Link to home
Start Free TrialLog in
Avatar of interclubs
interclubs

asked on

Sort Array Based on Date (PHP)

I have an array, with a key that is a date, like such 'Sun, 10 Jan 2010 00:51:30 +0000' and I want to sort the array so that I get most recent items first. I can make the date any format. I tried making it a timestamp, and then using ksort, but no luck.

Avatar of Cornelia Yoder
Cornelia Yoder
Flag of United States of America image

If you are sure you got a valid unix timestamp, then why didn't it work?  What went wrong?
Avatar of hielo
item at index zero will have the latest item
sorry, about that. Here you go:
<?php
function sortIt($a,$b){

	$a=strtotime($a);
	$b=strtotime($b);
	
	if($a==$b)return 0;
	return($a<$b?-1:1);
}
$data = array('Sun, 10 Jan 2010 00:51:30 +0000'=>'a'
			,'Sun, 10 Jan 2010 00:51:50 +0000'=>'c'
			,'Sun, 10 Jan 2010 00:51:40 +0000'=>'b'
			);
usort($data,"sortIt");
print_r($data);
?>

Open in new window

try this instead:
<?php
function sortIt($a,$b){

	$a=strtotime($a);
	$b=strtotime($b);
	
	if($a==$b)return 0;
	return($a<$b?1:-1);
}
$data = array('Sun, 10 Jan 2010 00:51:30 +0000'=>'a'
			,'Sun, 10 Jan 2010 00:51:50 +0000'=>'c'
			,'Sun, 10 Jan 2010 00:51:40 +0000'=>'b'
			);
uksort($data,"sortIt");
print_r($data);
?>

Open in new window

Avatar of interclubs
interclubs

ASKER

Hmmmm, what am I missing. I changed the date format to see if that would help. Here is a sample  array:

Array
(
    [0] => Array
        (
            [2010-01-10 16:45:33] => test
        )

    [1] => Array
        (
            [2010-01-10 06:01:02] => test
        )

    [2] => Array
        (
            [2010-01-10 00:51:30] => test
        )

    [3] => Array
        (
            [2010-01-09 22:38:54] => test
        )

    [4] => Array
        (
            [2010-01-09 07:49:00] => test
        )

    [5] => Array
        (
            [2010-01-10 23:38:36] => test
        )

    [6] => Array
        (
            [2010-01-09 19:47:12] => test
        )

    [7] => Array
        (
            [2009-12-31 14:42:29] => test
        )

    [8] => Array
        (
            [2009-12-29 16:07:34] => test
        )

    [9] => Array
        (
            [2009-12-28 14:05:53] => test
        )

)
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial