duanjianlu0506 2015-09-06 18:12
浏览 270
已采纳

根据日期/时间对数组进行排序

I am trying to sort a multidimensional array based on date/time, however it doesn't seem to be working correctly when I do a print_r. My best guess is that the time I provided to strtotime() is not in the correct format however the date and time formats are both listed, but separately in the php manual and no errors are thrown.

The format I use is unclear in the code so here it is: yyyy-mm-dd hhmm (24h with no colon GMT)

Here is the code:

function dateSort($a, $b){
    $d1 = strtotime($a['date'].' '.$a['startTime']);
    $d2 = strtotime($b['date'].' '.$a['startTime']);
    return $d1 - $d2;
}    
usort($events, 'dateSort');
print_r($events);
  • 写回答

2条回答 默认 最新

  • doutui2016 2015-09-06 20:54
    关注

    IVAO. You had a typo in third line of snippet. Second line refers to $a, but in 3rd you mix both $b and $a :).

    Also, I think, you needn't use strtotime at all. Look into snippet:

    <?php
    
    function dateSort($a, $b)
    {
        $d1 = floatval(str_replace('-', '', $a['date']) . " $a[startTime]");
        $d2 = floatval(str_replace('-', '', $b['date']) . " $b[startTime]");
        return $d1 - $d2;
    }
    
    $events = [
        ['date' => '2015-05-01', 'startTime' => '2300', 'value' => 'Event 1'],
        ['date' => '2012-05-01', 'startTime' => '1430', 'value' => 'Event 2'],
        ['date' => '2011-09-17', 'startTime' => '1021', 'value' => 'Event 3'],
        ['date' => '2001-01-22', 'startTime' => '0959', 'value' => 'Event 4'],
        ['date' => '1999-02-05', 'startTime' => '1740', 'value' => 'Event 5'],
    ];
    
    usort($events, 'dateSort');
    echo '<pre>' . print_r($events, 1) . '</pre>';
    

    And click to codepad.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?