questions on sort array by time in php

后端 未结 3 775
失恋的感觉
失恋的感觉 2020-12-11 02:19

---array $points----

Array
    (
        [0] => Array
            (
                [0] => 2011-10-02 05:30:00
                [1] =&         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 03:16

    The function uasort() takes a comparison callback function. You can use this to compare two timestamps.

    $arr = array(
            array('2011-10-02 05:30:00','20'),
            array('2011-10-04 09:30:00','12'),
            array('2011-10-01 13:30:00','25'),
            array('2011-10-03 02:30:00','31')
    );
    
    function timecomp($a,$b)
    {
        // Subtracting the UNIX timestamps from each other.
        // Returns a negative number if $b is a date before $a,
        // otherwise positive.
        return strtotime($b[0])-strtotime($a[0]);
    }
    uasort($arr,'timecomp');
    
    print_r($arr);
    

    The above code will return

    (
        [1] => Array
            (
                [0] => 2011-10-04 09:30:00
                [1] => 12
            )
    
        [3] => Array
            (
                [0] => 2011-10-03 02:30:00
                [1] => 31
            )
    
        [0] => Array
            (
                [0] => 2011-10-02 05:30:00
                [1] => 20
            )
    
        [2] => Array
            (
                [0] => 2011-10-01 13:30:00
                [1] => 25
            )
    
    )
    

提交回复
热议问题