Ví dụ
<?php
function compare_dates($time_1, $time_2) {
$t1 = strtotime($time_1);
$t2 = strtotime($time_2);
if ($t1 > $t2) return -1;
else if ($t1 < $t2) return 1;
else return 0;
}
$my_arr = array("2020-09-23", "2090-12-06", "2002-09-11", "2009-30-11");
usort($my_arr, "compare_dates");
print_r("The dates in sorted order is ");
print_r($my_arr);
?>
Kết quả
The dates in sorted order is
Array (
[0] => 2090-12-06
[1] => 2020-09-23
[2] => 2002-09-11
[3] => 2009-30-11
)
Giải thích
Hàm compare_dates chuyển chuỗi ngày thành timestamp bằng strtotime(), so sánh: trả về -1 nếu $time_1 > $time_2 (sắp giảm dần), 1 nếu nhỏ hơn, 0 nếu bằng. usort() sắp xếp mảng dùng hàm so sánh tùy chỉnh.
Lỗi dữ liệu đầu vào: "2009-30-11" ngày không hợp lệ (tháng 30). strtotime() có thể parse sai hoặc trả về false. Nên validate date trước hoặc dùng DateTime::createFromFormat().
Cách hiện đại (PHP 7+): Dùng usort($arr, fn($a,$b) => strtotime($a) <=> strtotime($b)) (spaceship operator) cho tăng dần, hoặc ngược lại cho giảm dần.