Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

โปรแกรม PHP เรียงลำดับวันที่ในรูปแบบอาร์เรย์


เพื่อเรียงลำดับวันที่ที่ให้มาในรูปแบบอาร์เรย์ใน PHP โค้ดมีดังนี้ −

ตัวอย่าง

<?php 
function compare_dates($time_1, $time_2) { 
    if (strtotime($time_1) > strtotime($time_2)) 
        return -1; 
    else if (strtotime($time_1) < strtotime($time_2)) 
        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); 
?>

ผลลัพธ์

The dates in sorted order is Array ( 
    [0] => 2090-12-06 
    [1] => 2020-09-23 
    [2] => 2002-09-11 
    [3] => 2009-30-11 
)

ฟังก์ชัน compare_dates รับรูปแบบเวลา 2 รูปแบบเป็นพารามิเตอร์ หากเวลาแรกมากกว่าคืน -1 หากน้อยกว่าคืน 1 มิฉะนั้นคืน 0 อาร์เรย์นิยามมีวันที่ต่างๆ ใช้ usort บนอาร์เรย์นี้ และแสดงวันที่เรียงแล้วบนคอนโซล