PHP生成排除指定时间段的一刻钟时间方案咨询
PHP 实现排除指定时间段后的可用时间序列
步骤1:实现生成时间序列的函数
先确保hoursRange函数能正确生成15分钟间隔的时间数组,格式统一为H:i:
function hoursRange($start, $end, $step = 15) { $times = []; $current = strtotime($start); $endTime = strtotime($end); while ($current <= $endTime) { $times[] = date('H:i', $current); $current += $step * 60; } return $times; }
步骤2:收集所有需要排除的时间点
遍历$klanten数组,把每个Time_start到Time_stop区间内的所有15分钟间隔时间收集起来,同时去重避免重复排除:
// 示例$klanten数组结构 $klanten = [ ['Time_start' => '09:00', 'Time_stop' => '10:30'], ['Time_start' => '14:15', 'Time_stop' => '15:00'], // 更多数据... ]; $excludedTimes = []; foreach ($klanten as $entry) { $startTimestamp = strtotime($entry['Time_start']); $stopTimestamp = strtotime($entry['Time_stop']); $current = $startTimestamp; while ($current <= $stopTimestamp) { $excludedTimes[] = date('H:i', $current); $current += 15 * 60; } } // 去重,避免同一时间被多次标记为排除 $excludedTimes = array_unique($excludedTimes);
步骤3:生成可用时间列表
先生成完整的08:00到21:00时间序列,再用array_diff移除排除项:
// 生成完整时间序列 $fullTimeRange = hoursRange('08:00', '21:00'); // 过滤得到可用时间 $availableTimes = array_diff($fullTimeRange, $excludedTimes); // 重新索引数组(可选) $availableTimes = array_values($availableTimes);
重复输出问题的原因
你之前的代码大概率是遍历每个时间段时就执行一次过滤并输出,导致同一可用时间被多次输出。先收集所有排除项,再一次性过滤完整列表,就能彻底避免重复问题。
内容的提问来源于stack exchange,提问作者Patrick_iot
相关产品推荐
相关产品推荐

