编程语言
首页 > 编程语言> > 如何检查PHP中多个日期范围之间的重叠?

如何检查PHP中多个日期范围之间的重叠?

作者:互联网

关于检查两个日期之间的重叠有很多帖子.但是,我找不到任何关于如何在多个范围内进行检查的讨论.

说我有这个数组:

$ranges = [
array('start'=>'2014-01-01' , 'end'=> '2014-01-05'),
array('start'=>'2014-01-06' > , 'end'=> '2014-01-10'),
array('start'=>'2014-01-04' > , 'end'=> '2014-01-07')]

可以简单地认为检查两个范围之间的重叠的函数可以在所有范围之间使用循环,但这是错误的,因为所有范围可以彼此重叠,但不是全部重叠.

我希望有人能帮我找到一个好的解决方案…..

解决方法:

<?php

// pass your ranges to this method and if there is a common intersecion it will
// return it or false

function checkIfOverlapped($ranges)
{
    $res = $ranges[0];

    $countRanges = count($ranges);

    for ($i = 1; $i < $countRanges; $i++) {

        $r1s = $res['start'];
        $r1e = $res['end'];

        $r2s = $ranges[$i]['start'];
        $r2e = $ranges[$i]['end'];

        if ($r1s >= $r2s && $r1s <= $r2e || $r1e >= $r2s && $r1e <= $r2e || $r2s >= $r1s && $r2s <= $r1e || $r2e >= $r1s && $r2e <= $r1e) {

            $res = array(
                'start' => $r1s > $r2s ? $r1s : $r2s,
                'end' => $r1e < $r2e ? $r1e : $r2e
            );

        } else return false;

    }

    return $res;
}

// example
$ranges = array(
    array('start' => '2014-01-01', 'end' => '2014-01-05'),
    array('start' => '2014-01-05', 'end' => '2014-01-10'),
    array('start' => '2014-01-04', 'end' => '2014-01-07')
);

var_dump(checkIfOverlapped($ranges));

标签:php,algorithm,date,overlap,overlapping
来源: https://codeday.me/bug/20190708/1405707.html