简体   繁体   中英

Detect overlapping periods php

can you help me with overlapping periods. I have array

["1-9","11-15","14-20","8-11"]

Each element in array its period. Min - 1 period, max - 10 periods in array. I need to detect if they are overlapping.

I find this cases from another question

形象

This is a simple snippet that way of its checking is based on comparing highest end of first range to lowest end of second range (if we only consider that ranges are valid). And at the first place, sorting ranges is playing an important role:

$ranges = ["1-9","11-15","14-20","8-11"];
$results = [];
sort($ranges, SORT_NUMERIC);
foreach ($ranges as $first) {
    $firstNums = explode("-", $first);
    foreach ($ranges as $second) {
        if ($first == $second) continue;
        $secondNums = explode("-", $second);
        if ($firstNums[1] >= $secondNums[0] && $first != end($ranges)) {
            $results[$first] = $second;
        }
    }
}
print_r($results);

Results (which contain both dates that overlap):

Array
(
    [1-9] => 8-11
    [8-11] => 11-15
    [11-15] => 14-20
)

This should cover all the scenarios :

<?php

public function findOverlappingPeriods(array $periods): array
{
    $overlappingItems = [];

    foreach ($periods as $keyA => $periodA) {
        foreach ($periods as $keyB => $periodB) {
            if ($keyA === $keyB) {
                continue;
            }

            if ($periodB['start'] > $periodA['start'] && $periodB['start'] < $periodA['end']) {
                $overlappingItems[] = $keyA;
                $overlappingItems[] = $keyB;
            }
        }
    }

    return $overlappingItems;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM