I have a simple problem: I need to sort an array of months and years by year (most recent first) then by month (Jan-Dec).
I have tried other ways, but with no luck.
The array being fed into my sorting function is 2 dimensional: each entry has a month and a 2 digit year, both as strings.
Here is my code:
Code: Select all
function sortByMonth($cur,$nxt){ //this works
global $list_months;//an array filled with 'jan','feb','mar',...
$mon_inv=array_flip($list_months);
return ($mon_inv[$cur[0]]<$mon_inv[$nxt[0]])?-1:1;
}
function sortBy2Year($cur,$nxt){ //this works
//cur and nxt as array('feb','08')
$y1=intval($cur[1]);
$y2=intval($nxt[1]);
return ($y1>$y2)?-1:1;
}
function sortByMonthYear($cur,$nxt){ //this doesn't work
$mon=sortByMonth($cur,$nxt);
$year=sortBy2Year($cur,$nxt);
$out=0;
if($mon==-1 && $year==-1)
$out=-1;
else if($mon==-1 && $year==1)
$out=1;
else if($mon==1 && $year==-1)
$out==-1;
else if($mon==1 && $year==1)
$out=1;
return $out;
}
function my_unique($arr){ //this works
//arr is of form array(array('feb','07'),array('jan','08'))
$out=array();
for($i=0;$i<count($arr);$i++){
$month=$arr[$i];
$m=$month[0];
$y=$month[1];
if(in_array($month,$out))
unset($arr[$i]);
else
$out[]=$month;
}
return $out;
}
$list_newsletters=my_unique(array_merge($docs_months,$pdfs_months)); //this works
usort($list_newsletters,"sortByMonthYear");//this doesn't workIs there a better way to do this that doesn't require calling usort twenty times?