Home >Backend Development >PHP Tutorial >How Can I Sort an Array of Objects by Date in PHP?
Sorting Arrays of Objects by Date
Problem:
One may encounter an array of objects with a 'date' field and the need to rearrange them based on the oldest date being at the start.
Solution Using PHP 5.3:
usort($array, function($a, $b) { return strtotime($a['date']) - strtotime($b['date']); });
This anonymous function compares the timestamps generated by 'strtotime' for each object's 'date' field and sorts them accordingly.
Solution for PHP Versions Prior to 5.3:
function cb($a, $b) { return strtotime($a['date']) - strtotime($b['date']); } usort($array, 'cb');
Define a custom comparison function 'cb' and pass it to 'usort' to sort the array based on the same timestamp comparison logic.
The above is the detailed content of How Can I Sort an Array of Objects by Date in PHP?. For more information, please follow other related articles on the PHP Chinese website!