Sometimes, we want to sort a multidimensional array by elements containing Y-m-d H:i:s date with PHP.
In this article, we’ll look at how to sort a multidimensional array by elements containing Y-m-d H:i:s date with PHP.
How to sort a multidimensional array by elements containing Y-m-d H:i:s date with PHP?
To sort a multidimensional array by elements containing Y-m-d H:i:s date with PHP, we use the strtotime
and usort
functions.
For instance, we write
function date_compare($a, $b)
{
$t1 = strtotime($a["datetime"]);
$t2 = strtotime($b["datetime"]);
return $t1 - $t2;
}
usort($array, "date_compare");
to call usort
with $array
and 'date_compare'
to sort the $array
in place with the date_compare
function as the comparator function.
In date_compare
, we convert the 'datetime'
values of $a
and $b
to timestamps with strtotime
.
Then we subtract the timestamps to compare them.
Conclusion
To sort a multidimensional array by elements containing Y-m-d H:i:s date with PHP, we use the strtotime
and usort
functions.