如何用PHP检查数组中的时间重叠事件?

时间:2015-05-25 09:21:32

标签: php arrays datetime

我正在使用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 个答案:

答案 0 :(得分:2)

请参阅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";
    }
}