PHP Sort a multidimensional array by element containing date
Solution 1:
Use usort()
and a custom comparison function:
function date_compare($a, $b)
{
$t1 = strtotime($a['datetime']);
$t2 = strtotime($b['datetime']);
return $t1 - $t2;
}
usort($array, 'date_compare');
EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.
usort
will pass two of these records to the given comparison function date_compare()
at a a time. date_compare
then extracts the "datetime"
field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0
if both dates are equal, a positive number if the first one ($a
) is larger or a negative value if the second argument ($b
) is larger. usort()
uses this information to sort the array.
Solution 2:
This should work. I converted the date to unix time via strtotime.
foreach ($originalArray as $key => $part) {
$sort[$key] = strtotime($part['datetime']);
}
array_multisort($sort, SORT_DESC, $originalArray);
One-liner version would be using multiple array methods:
array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
SORT_DESC,
$originalArray);
Solution 3:
From php7 you can use the Spaceship operator:
usort($array, function($a, $b) {
return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
});