【问题标题】:How to check time overlap event in array with PHP?如何使用 PHP 检查数组中的时间重叠事件?
【发布时间】:2015-05-25 09:21:32
【问题描述】:

我正在使用 while 打印带有 eventID、开始和结束时间的特定日期的事件。

如何使用 PHP 检查和打印哪个事件时间与哪个事件时间重叠?

<?php
while (list($key, $event_row) = each($events)) {
    $times_array = array(
        $event_row[0],
        date('Y-m-d H:i:s', $event_row[1]),
        date('Y-m-d H:i:s', $event_row[2])
    );
    print_r($times_array);
}

Array ( [0] => 11 [0] => 2015-05-29 19:00:00 [1] => 2015-05-29 21:00:00 )
Array ( [0] => 13 [0] => 2015-05-29 19:00:00 [1] => 2015-05-29 21:00:00 )
Array ( [0] => 16 [0] => 2015-05-29 21:00:00 [1] => 2015-05-29 22:00:00 )

我想要的示例输出是:

Event ID#: 11 overlaps with Event ID# 13.
Event ID#: 13 overlaps with Event ID# 11.
Event ID#: 16 doesn't overlap.

【问题讨论】:

  • 1.你的问题/问题是什么? 2. 你得到什么输出,你期望什么?
  • 你能发帖var_export($events)吗?
  • 数组 ( 0 => 数组 ( 0 => '11', 1 => 1432918800, 2 => 1432926000, ), 1 => 数组 ( 0 => '13', 1 => 1432918800 , 2 => 1432926000, ), 2 => 数组 ( 0 => '16', 1 => 1432926000, 2 => 1432929600, ), )

标签: php arrays datetime


【解决方案1】:

请参阅generic answer for checking if two date ranges overlap。对于 PHP,您需要将每个事件与所有其他事件进行比较,并通过测试检查是否存在冲突:

EndDate2 > StartDate1 AND EndDate1 > StartDate2

示例代码:

<?php
$events = array(
    array("11", 1432918800 /*2015-05-29 19:00:00*/, 1432926000 /*2015-05-29 21:00:00*/),
    array("13", 1432918800 /*2015-05-29 19:00:00*/, 1432926000 /*2015-05-29 21:00:00*/),
    array("16", 1432926000 /*2015-05-29 21:00:00*/, 1432929600 /*2015-05-29 22:00:00*/)
);
foreach ($events as $thisevent) {
    $conflicts = 0;
    foreach ($events as $thatevent) {
        if ($thisevent[0] === $thatevent[0]) {
            continue;
        }
        $thisevent_from = $thisevent[1];
        $thisevent_ends = $thisevent[2];
        $thatevent_from = $thatevent[1];
        $thatevent_ends = $thatevent[2];
        if ($thatevent_ends > $thisevent_from AND $thisevent_ends > $thatevent_from) {
            $conflicts++;
            echo "Event #" . $thisevent[0] . " overlaps with Event # " . $thatevent[0] . "\n";
        }
    }
    if ($conflicts === 0) {
        echo "Event #" . $thisevent[0] . " is OK\n";
    }
}

【讨论】:

  • 但是,如果有超过三个事件数组,我如何才能将此函数与我的事件数组变量一起使用?谢谢。
  • 我已经发布了足够多的代码。即兴发挥。
  • 我创建了这样的新事件数组,但它返回一切正常: $events[] = array("id" =>$event_row[0], "from" => date('Y-m-d H :i:s',$event_row[1]), "ends" => date('Y-m-d H:i:s',$event_row[2]));
  • 我更改了答案以匹配您的var_exported 输入。看看它是否有效。
猜你喜欢
  • 1970-01-01
  • 2016-06-20
  • 2016-08-25
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多