"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort an Array of Objects by Date in PHP?

How to Sort an Array of Objects by Date in PHP?

Published on 2024-11-09
Browse:609

How to Sort an Array of Objects by Date in PHP?

Sorting an Array of Objects by Date

In PHP, we often encounter the need to sort an array of objects by a specific property, such as a date field. This allows us to display or manipulate our data in chronological order.

Rearranging Objects by Date

Consider the following array of objects, where each object represents a record with a date property:

$array = [
    495 => (object)['date' => '2009-10-31 18:24:09'],
    582 => (object)['date' => '2010-2-11 12:01:42'],
];

To sort these objects by their date property in ascending order (oldest first), we can utilize the strtotime() function and the usort() function.

Custom Comparison Function

To use usort(), we need to define a custom comparison function that compares two objects based on their date property. The following code defines a function that subtracts the timestamp (converted using strtotime()) of the first object's date from the timestamp of the second object's date:

function cb($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}

Sorting the Array using usort()

Once we have our comparison function, we can call usort() on the array, passing in the comparison function as the second argument:

usort($array, 'cb');

Example

Using the example array from earlier, the resulting sorted array would be:

[
    495 => (object)['date' => '2009-10-31 18:24:09'],
    582 => (object)['date' => '2010-2-11 12:01:42'],
]

PHP 5.3 and Above

For PHP 5.3 and above, a simpler anonymous function can be used as the comparison function:

usort($array, function($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
});

This approach achieves the same sorting result as the previous one.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3