dqrb4228 2014-04-09 20:05
浏览 8
已采纳

在PHP中对工作日时间组合数组进行排序

I have an array in the form:

    $sortme = array(
        'Monday 10:00',
        'Friday 12:00',
        'Tuesday 14:00',
        'Monday 08:00',
        'Wednesday 11:00',
    );

The number of elements is unknown (so I couldn't use the uksort approach with a reference array for the order of weekdays as Mark suggested here). I want the result to be sorted chronologically and always starting with Monday like this:

    $sorted = array(
        'Monday 08:00',
        'Monday 10:00',
        'Tuesday 14:00',
        'Wednesday 11:00',
        'Friday 12:00',
    );

Is there an elegant way to do it without resorting to transform the array to a two-dimensional one and iterating? This would have been my only idea so far.

  • 写回答

4条回答 默认 最新

  • dragonlew9876 2014-04-09 20:16
    关注

    You can use usort function in PHP, which will do sorting using user-specified comparison function. The code below is probably not the most efficient, but it'll produce the correct result.

    $sortme = array(
            'Monday 10:00',
            'Friday 12:00',
            'Tuesday 14:00',
            'Monday 08:00',
            'Wednesday 11:00',
        );
    
    usort($sortme, function($a, $b) { return strcmp(date('N H:i', strtotime($a)), date('N H:i', strtotime($b))); });
    print_r($sortme);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?