Ranga
Ranga

Reputation: 3

Sorting Arrays of Arrays by useing date in php

$data = array( 
    array("firstname" => "Mary", "age" => 25,"date" => '14/07/2014 04:50'), 
    array("firstname" => "Amanda","age" => 18 ,"date" => '14/07/2014 13:20'), 
    array("firstname" => "James", "age" => 31 ,"date" => '10/07/2014 03:00'), 
    array("firstname" => "Patricia","age" => 7 ,"date" => '09/07/2010 06:32'), 
    array("firstname" => "Michael", "age" => 43 ,"date" => '10/01/2010 04:50'), 
    array("firstname" => "Ranga","age" => 23,"date"=> '08/06/1990 03:52' ),
    array("firstname" => "Sarah","age" => 24 ,"date" => '08/06/1991 04:25'), 
    array("firstname" => "Patrick","age" => 27 ,"date" => '19/07/2002 04:50'),
);

function compare_date($a, $b) { 
    return strnatcmp($a['date'], $b['date']); 
} 

usort($data, 'compare_date');

print_r($data);

It's not working. Please help.

Upvotes: 0

Views: 51

Answers (3)

dav
dav

Reputation: 9267

you should use dates in yyyy-mm-dd H:i:s format, for example, '2014-05-03 13:09:01'

when you compare two strings, it compares in natural order http://php.net/manual/en/function.strnatcmp.php. Consider this two dates 14/07/2014 04:50 and 20/07/2013 04:50,

if you compare like that, second one will be bigger, but as you can see the first one is bigger, because of the year 2014

edit: convert it to the necessary format during compare, like

date("Y-m-d H:i", strtotime('20/07/2013 04:50')) 

Upvotes: 0

George
George

Reputation: 36784

Use a couple of DateTime objects to compare the two values. You can create these objects using the DateTime::createFromFormat method:

function compare_date($a, $b) { 
    return DateTime::createFromFormat("d/m/Y H:i",$a['date']) > DateTime::createFromFormat("d/m/Y H:i",$b['date']); 
} 

Upvotes: 2

cornelb
cornelb

Reputation: 6066

Compare them by as dates, not natural order

function compare_date($a, $b) {
    return (strtotime(str_replace('/', '.', $a['date'])) < strtotime(str_replace('/', '.',   $b['date']))) ? -1 : 1;
}

14/07/2014 04:50 assumes 14 is the day and 7 is the month. But strtotime will see them the other way around. I am replacing / with . so

14/07/2014 04:50 becomes 14.07.2014 04:50

14.07.2014 04:50 will be interpreted properly by strtotime

Upvotes: 0

Related Questions