2011-08-18 48 views
2

我必须编写一个应该在两次之间开始和结束的循环。我知道有很多方法可以对这个猫进行皮肤处理,但是我希望看到真正的程序员使用这个功能。用PHP填充两次之间的空白

举例来说,我周三在下午6点开门,晚上10点30分关门。

我正在寻找一个循环,这将给我一个表,在15分钟的时间间隔,这两个之间的所有时间。

所以,我基本上是想建立一个列的表,其中每一行是

6:00pm 
6:15pm 
7:15pm 

等等

我的两个变量来养活这个功能将是,开放时间和结束时间。 现在不要指责我“写我的代码”张贴。我会很乐意给你我的黑客解决方案,我只想看看有真正经验的人会如何创建这个功能。

谢谢:)

回答

4
$start = new DateTime("2011-08-18 18:00:00"); 
$end = new DateTime("2011-08-18 22:30:00"); 
$current = clone $start; 
while ($current <= $end) { 
    echo $current->format("g:ia"), "\n"; 
    $current->modify("+15 minutes"); 
} 

尝试在键盘:http://codepad.org/JwBDOQQE

+2

这是一件美事。谢谢:)(我得等6分钟才能标记你是正确的,但是,它来了) –

+0

+1 - 虽然不是起始变量和克隆冗余吗? http://codepad.org/7LgqD2Mx – Gerry

+0

你的日期也是星期四,而问题是星期三。 ; D – Gerry

0
$start = strtotime('2011-08-11 18:00:00'); 

for ($i = 0; $i < 20; $i++) { 
    echo date('g:ia', $start + ($i * (15 * 60))), '<br>'; 
} 
+0

我见过你给可爱的动物(不是这个)为什么20?它来自哪里? –

+0

只是一些随机的结束值。在这种情况下,它将输出20:15分钟的间隔。 –

+0

但并未提出请求 –

3

PHP 5.3引入了类正是为了这个目的,DatePeriod

$start = new DateTime("6:00pm"); 
$end  = new DateTime("10:30pm"); 
$interval = new DateInterval('PT15M'); 
$period = new DatePeriod($start, $interval, $end); 

foreach ($period as $time) { 
    echo $time->format('g:ia'), PHP_EOL; 
} 

echo $end->format('g:ia'); // end time is not part of the period 
+0

他周三说; P – Gerry

+0

@Gerry,在提到星期三之后记下“例如”。根据情况更改开始/结束日期/时间并不重要。 – salathe

+0

我注意到了,我只是在逗弄。 – Gerry