创建循环时间增加15分钟

sca*_*and 10 php time date

我正在尝试创建一个输出这个的循环:

08:00
08:15
08:30
08:45
09:00
09:15
09:30
09:45
Run Code Online (Sandbox Code Playgroud)

我需要它从08:00到17:00

到目前为止我的代码:

function echo_datelist ($i, $j, $day, $month, $year)
{
    $time = str_pad($i, 2, '0', STR_PAD_LEFT).':'.str_pad($j, 2, '0', STR_PAD_LEFT);            
    $date = strtotime("$month $day $year $time:00");
    $sql = mysql_query("select b.room_type, c.name from bookings as b, customers as c where b.the_date='$date' and b.id_customer=c.id");

    echo $time.'<br />';
}

for ($i = 8; $i <= 16; $i++)
{
    for ($j = 0; $j <= 45; $j+=15)
        echo_datelist($i, $j, $day, $month, $year);

    echo_datelist(17, 0, $day, $month, $year);
}
Run Code Online (Sandbox Code Playgroud)

问题是,它在每小时之间输出17:00,例如:

08:00
08:15
08:30
08:45
17:00
09:00
09:15
09:30
09:45
17:00
Run Code Online (Sandbox Code Playgroud)

小智 15

它也可以使用范围功能完成

<?php
date_default_timezone_set("Europe/London");
$range=range(strtotime("08:00"),strtotime("17:00"),15*60);
foreach($range as $time){
        echo date("H:i",$time)."\n";
}
?>
Run Code Online (Sandbox Code Playgroud)

所以你没有一个循环,它只为你创建一个数组(我的循环只是在格式化时打印出来)


Ric*_*ard 12

看起来对我来说不必要的复杂.以下将打印出您想要的内容.据推测,它可以适用于您的代码.对于凌乱的最终条件感到抱歉.

$min=array("00","15","30","45");

for($i=8;$i<17;$i++)
  foreach ($min as $v)
    print "$i:$v\n";
print "17:00\n";
Run Code Online (Sandbox Code Playgroud)

或者,如果你想以稍微不透明的方式做到这一点......

for($i=8*60;$i<=17*60;$i+=15)
  print floor($i/60) . ":" . ($i/60-floor($i/60))*60 . "\n";
Run Code Online (Sandbox Code Playgroud)

以上计算8点钟的分钟值,然后反复增加15分钟.然后使用一些数学运算从运行变量中提取小时和分钟.


小智 9

我的简单逻辑

   $start=strtotime('00:00');
   $end=strtotime('23:30');

    for ($i=$start;$i<=$end;$i = $i + 15*60)
    {

     //write your if conditions and implement your logic here

     echo date('g:i A',$i).'<br>';

    }
Run Code Online (Sandbox Code Playgroud)

在循环中,你可以发挥你想要的


Gaz*_*ler 8

您需要移动外部for循环外的最后一行.

for ($i = 8; $i <= 16; $i++){
  for ($j = 0; $j <= 45; $j+=15){
    //inside the inner loop
    echo_datelist($i, $j, $day, $month, $year);
  }
  //inside the outer loop
}
//outside the outer loop
echo_datelist(17, 0, $day, $month, $year);
Run Code Online (Sandbox Code Playgroud)

简单来说,你说:

For each hour between 8 and 16
  For each 15 minute interval
    Echo the time
  End
  Echo 17:00
End
Run Code Online (Sandbox Code Playgroud)

代替:

For each hour between 8 and 16
  For each 15 minute interval
    Echo the time
  End
End
Echo 17:00
Run Code Online (Sandbox Code Playgroud)

我会考虑在一天中的所有时间执行您的SQL查询,然后在时间内挑选出来,否则您每隔15分钟就会进行一次SQL查询(对您的示例数据进行37次查询)