Here is some few methods:
$array_to_sort_1 = array(
"11-01-2012",
"01-01-2014",
"01-01-2015",
"09-02-2013",
"01-01-2013"
);
fnc_sort_1($array_to_sort_1,"asc","d-m-Y");
// var_dump($array_to_sort_1); // * uncomment to test
$array_to_sort_2 = array(
array( "user"=>"user1", "date_str"=>"11-01-2012", "comment"=>"1" ),
array( "user"=>"Donny", "date_str"=>"01-01-2014", "comment"=>"4" ),
array( "user"=>"Frenk", "date_str"=>"01-01-2015", "comment"=>"5" ),
array( "user"=>"Axvel", "date_str"=>"01-01-2013", "comment"=>"2" ),
array( "user"=>"Johny", "date_str"=>"09-02-2013", "comment"=>"3" )
);
fnc_sort_2($array_to_sort_2,"asc","d-m-Y");
// var_dump($array_to_sort_2); // * uncomment to test
$array_to_sort_3 = array(
array( "user"=>"user1", "date_str"=>"11.01.2012 12:54", "comment"=>"1" ),
array( "user"=>"Donny", "date_str"=>"01.01.2014 12:54", "comment"=>"4" ),
array( "user"=>"Frenk", "date_str"=>"01.01.2015 12:54", "comment"=>"5" ),
array( "user"=>"Johny", "date_str"=>"09.02.2013 12:53", "comment"=>"2" ),
array( "user"=>"Axvel", "date_str"=>"09.02.2013 12:54", "comment"=>"3" )
);
fnc_sort_2($array_to_sort_3,"asc","d.m.Y H:i");
// var_dump($array_to_sort_3); // * uncomment to test
/**
* * DateTime::createFromFormat("d.m.Y H:i", $date_str);
* * $in_direction ["asc","desc"]
*/
function fnc_sort_1(array &$in_arr, $in_direction = "asc", $in_dt_format = "Y-m-d H:i"){
usort($in_arr, function($a, $b) use($in_direction,$in_dt_format){
$v_desc = "desc";
$v_asc = "asc";
$dt_format = "Y-m-d H:i:s";
$a1 = DateTime::createFromFormat($in_dt_format, $a);
$b1 = DateTime::createFromFormat($in_dt_format, $b);
$a2 = $a1->format($dt_format) ;
$b2 = $b1->format($dt_format) ;
$a3 = strtotime($a2) ;
$b3 = strtotime($b2) ;
if($in_direction===$v_desc){
return $b3 - $a3; // * Desc
}else if ($in_direction===$v_asc){
return $a3 - $b3; // * Asc
}
return 0;
});
}
/**
* * DateTime::createFromFormat("d.m.Y H:i", $date_str);
* * $in_direction ["asc","desc"]
*/
function fnc_sort_2(array &$in_arr, $in_direction = "asc", $in_dt_format = "Y-m-d H:i"){
usort($in_arr, function($a, $b) use($in_direction,$in_dt_format){
$v_desc = "desc";
$v_asc = "asc";
$dt_format = "Y-m-d H:i";
$a1 = DateTime::createFromFormat($in_dt_format, $a["date_str"]);
$b1 = DateTime::createFromFormat($in_dt_format, $b["date_str"]);
$a2 = $a1->format($dt_format) ;
$b2 = $b1->format($dt_format) ;
$a3 = strtotime($a2) ;
$b3 = strtotime($b2) ;
if($in_direction===$v_desc){
return $b3 - $a3; // * Desc
}else if ($in_direction===$v_asc){
return $a3 - $b3; // * Asc
}
return 0;
});
}
d-m-Y
orm-d-Y
. – Crinose$a
and$b
instead of trying to access a date property. – Crinose