我有一个有趣的问题,应该很有趣。
使用PHP7,但实际上任何语言都可以,只需要一个坚实的模式即可。
我们有一个应用程序,允许用户添加时间表,该时间表以00:00
开始,以23:45
结束,以15分钟为增量。
我们最终得到了一系列选定的时间,需要考虑到差距将其映射到范围,差距是我的问题。
所以,我需要一个模式/函数,它将返回一组合并的时间范围。
例如,以下范围:
00:00
00:15
00:30
00:45
01:00
<gap>
02:00
02:15
02:30
将减少为:
00:00-1:00
02:00-02:30
等
这是我的第一次尝试:
$test = ['00:00','00:15','00:30','01:00','01:15','01:30','01:45','02:00','02:15','02:45'];
$inc = 15*60;
$start = $test[0];
for($x=0; $x<count($test); $x++) {
if(strtotime($test[$x]) + $inc != strtotime($test[$x+1])) {
if($test[$x] == '23:45') // special case
$end = '23:59:59';
else
$end = date('H:i', strtotime($test[$x]) + $inc); // add back 15 minutes to capture full hour
$final[] = $start . '-' . $end;
$start = $test[$x+1];
}
}
var_dump($final);
输出:
array(3) {
[0]=>
string(11) "00:00-00:45"
[1]=>
string(11) "01:00-02:30"
[2]=>
string(11) "02:45-03:00"
}
感谢您的反馈!