I have an array of dates and I have to sort it by using the described functions.
Here is what I have:
$dates = array (\'10-10-2003\', \'2-17-2002\', \'2-
Here's an alternate solution for you.
<?php
$dates = array(
'10-10-2003',
'2-17-2002',
'2-16-2003',
'1-01-2005',
'10-10-2004',
);
function toTime($date) {
list($month, $day, $year) = explode('-', $date);
return mktime(0, 0, 0, $month, $day, $year);
}
function sortByTime($a, $b) {
$a = toTime($a);
$b = toTime($b);
if($a == $b) {
return 0;
}
return $a < $b ? -1 : 1 ;
}
usort($dates, 'sortByTime');
print_r($dates);
/*
Array
(
[0] => 2-17-2002
[1] => 2-16-2003
[2] => 10-10-2003
[3] => 10-10-2004
[4] => 1-01-2005
)
*/
In your date_tim_timestamp function, you are essentially throwing away your date in place of the integer value.
Try this instead:
function date_to_timestamp($d){
$newarr = array();
foreach($d as $f) {
$arr=explode("-",$f);
//array_push($newarr, mktime(0,0,0,$arr[0],$arr[1],$arr[2]));
$int_version = mktime(0,0,0,$arr[0],$arr[1],$arr[2]);
$newarr[$int_version] = $f;
}
return $newarr;
}
Using this approach, you wont need to use usort(), just ksort()