【问题标题】:Excluding specific half hour from the list of half hours从半小时列表中排除特定半小时
【发布时间】:2014-03-20 15:23:23
【问题描述】:

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

$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
        )
)

我需要有关如何执行此操作的帮助,任何帮助将不胜感激

【问题讨论】:

    标签: php arrays datetime for-loop


    【解决方案1】:

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

    <?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

    【讨论】:

    • 哇!约翰今天早上很无聊。
    • 大声笑。其实我有点://
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多