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

เรียงลำดับ Array ของวันที่ใน PHP


เพื่อเรียงลำดับ array ของวันที่ใน PHP โค้ดมีดังนี้ −

ตัวอย่าง

<?php 
    function compareDates($date1, $date2){ 
        return strtotime($date1) - strtotime($date2); 
    } 
    $dateArr = array("2019-11-11", "2019-10-10","2019-08-10", "2019-09-08"); 
    usort($dateArr, "compareDates"); 
    print_r($dateArr); 
?>

ผลลัพธ์

จะผลลัพธ์ดังนี้ −

Array ( 
    [0] => 2019-08-10 
    [1] => 2019-09-08 
    [2] => 2019-10-10 
    [3] => 2019-11-11 )

ตัวอย่าง

มาดูตัวอย่างอีกอย่าง −

<?php 
    function compareDates($date1, $date2){ 
        if (strtotime($date1) < strtotime($date2)) 
            return 1; 
        else if (strtotime($date1) > strtotime($date2)) 
            return -1; 
        else 
            return 0; 
    } 
    $dateArr = array("2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11", "2019-01-01"); 
    usort($dateArr, "compareDates"); 
    print_r($dateArr); 
?>

ผลลัพธ์

จะผลลัพธ์ดังนี้ −

Array ( 
    [0] => 2019-11-11 
    [1] => 2019-11-11 
    [2] => 2019-10-10 
    [3] => 2019-09-08 
    [4] => 2019-05-11 
    [5] => 2019-01-01 )