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

Susan Sarandon
Release: 2024-10-27 00:02:02
Original
764 people have browsed it

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']);
});
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!