基于2小时时间差分组时间数组,生成起止时间段
搞定按2小时间隔生成时间段分组的问题
嘿,我来帮你解决这个时间分组的需求!先把咱们的核心规则捋明白:
- 直接忽略那些跟前后任何时间都凑不出恰好2小时间隔的项(比如你数组里第一个
2019-04-01 00:00:00,跟下一个时间差了好几天,肯定要被踢出去) - 对于连续的、每相邻两个时间正好差2小时的序列,咱们可以把它们合并成一个完整的时间段;要是你想要每两个相邻的单独成组,也能调整逻辑实现
下面我基于你现有的PHP代码做了扩展,假设$finaltime已经是你筛选好的、没有事件的时间段数组(就是你代码里$result_set == 0的那些项):
完整代码实现(合并连续序列为大分组)
// 假设$finaltime已经是筛选后的无事件时间数组 $timeGroups = []; $totalTimes = count($finaltime); if ($totalTimes === 0) { print_r($timeGroups); exit; } // 先把第一个时间当作当前分组的起始点 $currentGroupStart = $finaltime[0]; for ($i = 1; $i < $totalTimes; $i++) { // 把时间转成时间戳,方便算间隔 $prevTimestamp = strtotime($finaltime[$i-1]); $currTimestamp = strtotime($finaltime[$i]); $timeDiff = $currTimestamp - $prevTimestamp; // 判断是不是正好2小时(7200秒) if ($timeDiff == 7200) { // 符合间隔,把当前时间设为分组的结束点 $currentGroupEnd = $finaltime[$i]; } else { // 不符合间隔,先把之前的有效分组存起来 if (isset($currentGroupEnd)) { $timeGroups[] = [ 'formdate' => $currentGroupStart, 'todate' => $currentGroupEnd ]; } // 重置分组起始点,开始新的一轮判断 $currentGroupStart = $finaltime[$i]; unset($currentGroupEnd); } } // 循环结束后,别忘了把最后一个有效分组也存进去 if (isset($currentGroupEnd)) { $timeGroups[] = [ 'formdate' => $currentGroupStart, 'todate' => $currentGroupEnd ]; } // 打印结果,方便查看 echo '<pre>'; print_r($timeGroups); echo '</pre>';
代码咋工作的?
- 时间差计算:用
strtotime()把字符串时间转成时间戳,直接算差值是不是7200秒(刚好2小时),简单粗暴不出错 - 分组逻辑:
- 碰到符合2小时间隔的,就把当前时间设为分组的结束点,继续往后找
- 碰到不符合的,就把之前攒好的分组存进结果,然后重置起始点重新来
- 循环完了一定要检查最后一个分组,别漏了
- 自动忽略无效项:像第一个时间那样,前后都凑不出2小时间隔的,根本不会被放进任何分组,自然就被忽略了
针对你给的数组的输出结果
假设你数组里的项都符合$result_set == 0的条件,运行上面的代码会得到:
Array ( [0] => Array ( [formdate] => 2019-04-07 06:00:00 [todate] => 2019-04-07 22:00:00 ) [1] => Array ( [formdate] => 2019-04-08 00:00:00 [todate] => 2019-04-08 22:00:00 ) )
要是你想要每两个相邻的单独成组?
比如你示例里那种10:00-12:00的单独分组,那就换下面这段代码,每次碰到符合间隔的就直接存一个分组:
$timeGroups = []; $totalTimes = count($finaltime); for ($i = 0; $i < $totalTimes - 1; $i++) { $prevTimestamp = strtotime($finaltime[$i]); $nextTimestamp = strtotime($finaltime[$i+1]); $timeDiff = $nextTimestamp - $prevTimestamp; if ($timeDiff == 7200) { $timeGroups[] = [ 'formdate' => $finaltime[$i], 'todate' => $finaltime[$i+1] ]; } } // 打印结果 echo '<pre>'; print_r($timeGroups); echo '</pre>';
这样运行后,会生成从06:00-08:00、08:00-10:00一直到20:00-22:00的所有相邻2小时分组,第一个无效的时间也会自动被忽略。
内容的提问来源于stack exchange,提问作者Ritesh Shirsat
相关产品推荐
相关产品推荐

