You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP生成预约时段列表时while循环陷入死循环问题求助

解决PHP预约时段列表的无限循环问题

嘿,我来帮你搞定这个无限循环的坑~

你遇到的问题根源很明确:在循环里把时间戳变量$st改成了字符串类型,导致循环条件的比较彻底失效了。

问题分析

原代码中,你写了:

echo $st = date( "H:i", strtotime('+30 minutes', $st) );

这里date()函数返回的是格式化后的字符串(比如"09:30"),你把这个字符串赋值回了$st。而$et是strtotime($endTime)得到的整数时间戳(比如19:00对应的时间戳是一个很大的数字)。

当PHP比较字符串和整数时,会把字符串转换成整数——而像"09:30"这样的字符串转成整数结果是0。所以循环条件$st < $et就变成了0 < 大数字,永远为真,自然就无限循环了。

修复方案

核心思路是:保持$st始终为时间戳(整数),只把格式化后的字符串用于输出,不要覆盖$st的类型。

修复后的基础版本

<?php 
$startTime = "9:00:00"; 
$endTime = "19:00:00"; 
$st = strtotime($startTime); 
$et = strtotime($endTime); 

while ($st < $et) { 
    // 计算下一个30分钟的时间戳
    $nextTimestamp = strtotime('+30 minutes', $st);
    // 格式化并输出时段
    echo date("H:i", $nextTimestamp) . '<br>';
    // 更新$st为下一个时间戳,推进循环
    $st = $nextTimestamp;
} 
?>

更优雅的DateTime版本(推荐)

用PHP的DateTime类处理时间会更直观,避免类型转换的问题,代码可读性也更高:

<?php
$start = new DateTime("9:00:00");
$end = new DateTime("19:00:00");
// 定义30分钟的时间间隔
$interval = new DateInterval("PT30M");

while ($start < $end) {
    $start->add($interval);
    echo $start->format("H:i") . '<br>';
}
?>

效果验证

不管用哪个版本,最终都会输出从09:30到18:30的所有30分钟间隔时段,循环会在$st(或$start)达到19:00时自动终止,完美解决无限循环问题。

内容的提问来源于stack exchange,提问作者Tugce Aksoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:07:33