简体   繁体   English

检测重叠时期php

[英]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.最小 - 1 个周期,最大 - 数组中的 10 个周期。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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