Sort an array of dates using usort() and sort() functions by the timestamp converted by mktime()

前端 未结 2 676
猫巷女王i
猫巷女王i 2021-01-26 11:59

I have an array of dates and I have to sort it by using the described functions.

Here is what I have:

$dates = array (\'10-10-2003\', \'2-17-2002\', \'2-         


        
相关标签:
2条回答
  • 2021-01-26 12:19

    Here's an alternate solution for you.

    <?php
    $dates = array(
        '10-10-2003',
        '2-17-2002',
        '2-16-2003',
        '1-01-2005',
        '10-10-2004',
    );
    
    function toTime($date) {
        list($month, $day, $year) = explode('-', $date);
        return mktime(0, 0, 0, $month, $day, $year);
    }
    
    function sortByTime($a, $b) {
        $a = toTime($a);
        $b = toTime($b);
        if($a == $b) {
            return 0;
        }
        return $a < $b ? -1 : 1 ;
    }
    
    usort($dates, 'sortByTime');
    
    print_r($dates);
    
    /*
        Array
        (
            [0] => 2-17-2002
            [1] => 2-16-2003
            [2] => 10-10-2003
            [3] => 10-10-2004
            [4] => 1-01-2005
        )
    */
    
    0 讨论(0)
  • 2021-01-26 12:27

    In your date_tim_timestamp function, you are essentially throwing away your date in place of the integer value.

    Try this instead:

    function date_to_timestamp($d){
        $newarr = array();
        foreach($d as $f) {
            $arr=explode("-",$f);
            //array_push($newarr, mktime(0,0,0,$arr[0],$arr[1],$arr[2]));
            $int_version = mktime(0,0,0,$arr[0],$arr[1],$arr[2]);
            $newarr[$int_version] = $f;
        }
        return $newarr;
    }
    

    Using this approach, you wont need to use usort(), just ksort()

    0 讨论(0)
提交回复
热议问题