doujuxin7392 2016-10-31 14:04
浏览 63
已采纳

从最接近的星期几开始对PHP数组进行排序

I have a PHP array of days of the week:

$dow = array( 2, 3, 4, 6, 7 );

This array is generated dynamically. So it may be the values above, or it may be a slightly altered version.

I need to show the next week, with the days in that array highlighted, but it needs to be done starting with the current day.

So if today's day of the week is later, and I use the above array to get the next Tuesday, Wednesday, etc, then I end up missing the end of the current week.

Super short example:

$today = date();
foreach $dow as $id => $weekday:
    // display next $weekday after $today
endforeach;

So if today is Wednesday, then this will end up skipping Thurs, Sat, and Sun and start with Tuesday.

I can only figure out two possible ways to do this, and I'm not sure how to do either one. Either sort the array starting with the next day of the week and put the other ones at the end of the array, or get the starting position, loop through the rest of the array, then loop through the array again until I've hit that starting position.

How do I get the next week's worth of these days?

  • 写回答

1条回答 默认 最新

  • dongtao4787 2016-10-31 14:12
    关注
    $today = date('N');
    
    foreach ($dow as $key => $value) {
        if ($value >= $today) {
            break;
        }
    }
    
    $dow = array_merge(array_slice($dow, $key), array_slice($dow, 0, $key));
    

    If today is 4, the array is now:

    array(4, 6, 7, 2, 3)
    

    You just need to loop over it in order now.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式