Home >Backend Development >PHP Tutorial >How Can I Sort an Array of Objects by Date in PHP?

How Can I Sort an Array of Objects by Date in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 00:02:02880browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn