1

下面是一个 FOR 循环的代码,它呈现出一个时间列表,如下所示:

...etc...
8:45 am
8:50 am
8:55 am
9:00 am
9:05 am
9:10 am
...etc.

这是一个运行 5 分钟间隔的脚本,目前这个脚本没有问题,因为它可以被 60 整除。但是,我需要将它设置在可以使该时间间隔达到任何我想要的量的地方,例如 9 分钟. 我尝试更改 for ($j >= 0; $j <= 55; $j+=5) for ($j >= 0; $j <= 59; $j+=9)希望输出:

...etc...
8:36 am
8:45 am 
8:54 am
9:03 am
9:12 am
9:21 am
...etc

我希望它延续到下一小时并像上面一样继续......并注意第一个小时是如何开始的术语,这就是我想要做的.. 但是它只输出到小于或等于 59 之前的最后一个值,然后退出:即

...etc...
8:36 am
8:45 am
8:54 am
---AND STOPS HERE---

以上是它的回声方式。

下面是我的代码:

$day = date("n/j/y");

            $startTime = date(strtotime($day." $coursetee_open_time_slashed"));
            ///needs to be in "16:00" format
            $endTime = date(strtotime($day." $coursetee_close_time_slashed"));
            ///needs to be in "16:00" format

            $timeDiff = round(($endTime - $startTime)/60/60);

            $startHour = date("G", $startTime);
            $endHour = $startHour + $timeDiff; 

            for ($i=$startHour; $i <= $endHour; $i++)
                {
                    for ($j >= 0; $j <= 55; $j+=5)
                    {
                        $time_pre = $i.":".str_pad($j, 2, '0', STR_PAD_LEFT);
                        $time = ''.$time_pre .' '.$day.'';

                        /////////////////////////////

                        $time_formated_for_cosmetic = date("g:i a", strtotime("$time"));
                        $time_formated_for_mysql = date("Y-m-d H:i:s", strtotime("$time"));
                            if (isset($tee_times_from_mysql[$time])) {
                                $time = '';
                            } else {
                                $time = '<option value="' . $time_formated_for_mysql . '">'.$time_formated_for_cosmetic .'</option>';
                            }
                            echo $time;
                    }

            }
4

2 回答 2

2
$increment = 9;
$j = 0;
for ($i=$startHour; $i <= $endHour; $i++)
{
    for (; $j < 60; $j += $increment) // $j initialized outside of loop
    {
         // ...
    }
    $j -= 60; // Get start minute for next hour
}
于 2013-06-06T18:20:27.493 回答
1

您可以在 for 循环中使用时间戳:

$day = date("n/j/y");

$coursetee_open_time_slashed = "16:00";
$coursetee_close_time_slashed = "18:00";


$startTime = strtotime($day." $coursetee_open_time_slashed"); // timestamp
// needs to be in "16:00" format
$endTime = strtotime($day." $coursetee_close_time_slashed"); // timestamp
// needs to be in "16:00" format

for ($time = $startTime; $time < $endTime; $time += 60 * 5) {
    echo date("Y-m-d H:i:s", $time) . "\n";
}
于 2013-06-06T18:23:49.947 回答