PHP开始时间和结束时间之间的时间循环

Ami*_*ani 2 php time loops

我有这个功能,它给我一个选择输入中的一组选项.选项给我时间间隔为5分钟.问题是当时间如23:45时,选项将从00:10开始并基于$ j变量循环.

这就是我想用的话:在$ open_time到$ close_time的5分钟间隔内给我一个选项列表.如果当前时间($ timeNow)大于$ open_time,则将$ open_time设置为$ timeNow以显示为第一个选项.只在$ close_time之前执行此循环.

我希望这很清楚.感谢您的帮助 :)

这是代码:

function selectTimesofDay(){
    $output = "";
    $now = date('G:i ', time()); // time now
    $timeNow = strtotime($now); // strtotime now
    $next_five = ceil($timeNow / 300) * 300; // get next 5 minute
    // time now rounded to next 10 minute
    $round5minNow = date('G:i', strtotime('+15 minutes',$next_five)); 
    $open_time = strtotime('17:00');
    $close_time = strtotime('23:59');

    // in the middle of working hours, time sets to current
    if($timeNow >= $open_time && $timeNow < $close_time){
        $open_time = strtotime($round5minNow);
     }
    $time_diff = round(($close_time - $open_time)/60) ; 
    if(date('l') == 'Friday'){
        $j = ($time_diff/5)+11; // working hours extended untill 1:00 AM
    } else{
        $j = ($time_diff/5)-1; // working hours untill 12:00 AM
    }

        for($i = 0; $i <= $j; $i++){
            $b = $i*5;  
            $data = date('l')." - ".date("H:i", strtotime('+'.$b.' minutes', $open_time));
            $output .= "<option value=\"{$data}\">";    
            $output .= $data;
            $output .= "</option>";
        }

    return $output;
}
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 8

你真正需要的是:

function selectTimesOfDay() {
    $open_time = strtotime("17:00");
    $close_time = strtotime("23:59");
    $now = time();
    $output = "";
    for( $i=$open_time; $i<$close_time; $i+=300) {
        if( $i < $now) continue;
        $output .= "<option>".date("l - H:i",$i)."</option>";
    }
    return $output;
}
Run Code Online (Sandbox Code Playgroud)

所以这样做是在开始和结束之间每五分钟间隔运行一次循环检查.如果它在临时之前跳过它,否则添加一个选项.

它比你想做的更有效,也可能更容易理解.

你甚至可以把它放在循环之后:

if( $output == "") return "<option disabled>Sorry, we're closed for today</option>";
Run Code Online (Sandbox Code Playgroud)

另外,请注意我是如何一直遗漏value属性的.那是因为在没有a的情况下value,选项的文本被用作值.因此,该解决方案避免了不必要的重复.