从半小时列表中排除特定半小时

时间:2014-03-20 15:23:23

标签: php arrays datetime for-loop

我有一个循环,它给出了给定开始时间和结束时间之间半小时的结果

$start    = new DateTime('09:00:00');
// add 1 second because last one is not included in the loop
$end      = new DateTime('16:00:01'); 
$interval = new DateInterval('PT30M');
$period   = new DatePeriod($start, $interval, $end);

$previous = '';
foreach ($period as $dt) {
    $current = $dt->format("h:ia");
    if (!empty($previous)) {
        echo "<input name='time' type='radio' value='{$previous}|{$current}'> 
              {$previous}-{$current}<br/>";
    }
    $previous = $current;
}

上述循环的结果如下

09:00am-09:30am
09:30am-10:00am
10:00am-10:30am
10:30am-11:00am
11:00am-11:30am
11:30am-12:00pm
12:00pm-12:30pm
12:30pm-01:00pm
01:00pm-01:30pm
01:30pm-02:00pm
02:00pm-02:30pm
02:30pm-03:00pm
03:00pm-03:30pm
03:30pm-04:00pm

我想要实现的是排除下面提到的一些时间,如果它存在于另一个看起来像这样的数组$existing_time

    [0] => Array
        (
            [start_time] => 2014-03-28T14:00:00+1100
            [end_time] => 2014-03-28T14:30:00+1100
        )

    [1] => Array
        (
            [start_time] => 2014-03-28T15:00:00+1100
            [end_time] => 2014-03-28T15:30:00+1100
        )
)

我需要帮助,如何做到这一点,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

我刚刚将开始时间添加到数组中,然后检查当前开始时间是否在该数组中。如果是这样,我们跳过它。

<?php
$start    = new DateTime('09:00:00');
$end      = new DateTime('16:00:01'); // add 1 second because last one is not included in the loop
$interval = new DateInterval('PT30M');
$period   = new DatePeriod($start, $interval, $end);

$existing_time = array(
    array(
        'start_time' => '2014-03-28T14:00:00+1100',
        'end_time' => '2014-03-28T14:30:00+1100'
    ),
    array(
        'start_time' => '2014-03-28T15:00:00+1100',
        'end_time' => '2014-03-28T15:30:00+1100'
    )
);

$booked = array();
foreach ($existing_time as $ex) {
    $dt = new DateTime($ex['start_time']);
    $booked[] = $dt->format('h:ia');
}

$previous = '';
foreach ($period as $dt) {
    $current = $dt->format("h:ia");
    if (!empty($previous) && !in_array($previous, $booked)) {
        echo "<input name='time' type='radio' value='{$previous}|{$current}'> {$previous}-{$current}<br/>";
    }
    $previous = $current;
}

See it in action

相关问题