Sorting an array with DateTime strings?
14,701
Solution 1
Have you looked at the usort
Docs function? It lets you define a callback function to compare two values. So I'm suggesting something along these lines:
function compare_func($a, $b)
{
// CONVERT $a AND $b to DATE AND TIME using strtotime() function
$t1 = strtotime($a["end_time"]);
$t2 = strtotime($b["end_time"]);
return ($t2 - $t1);
}
usort(main_array, "compare_func");
Solution 2
usort($data, function($a, $b) {
return strtotime($a['end_time']) - strtotime($b['end_time']);
});
Solution 3
usort($array, function($a, $b){
return (strtotime ($a ['end_time'])
- strtotime ($b ['end_time']))
* -1;
});
Author by
gremo
Updated on June 25, 2022Comments
-
gremo almost 2 years
How can i sort efficiently this array (recent items first) on
end_time
value in PHP?array 0 => array 'value' => int 4 'end_time' => string '2012-01-20T08:00:00+0000' (length=24) 1 => array 'value' => int 0 'end_time' => string '2012-01-21T08:00:00+0000' (length=24) 2 => array 'value' => int 5 'end_time' => string '2012-01-22T08:00:00+0000' (length=24) 3 => array 'value' => int 4 'end_time' => string '2012-01-23T08:00:00+0000' (length=24) 4 => array 'value' => int 7 'end_time' => string '2012-01-24T08:00:00+0000' (length=24)