["1-9","11-15","14-20","8-11"]
数组中的每个元素的周期。最小 - 1个周期,最多 - 阵列中的10个周期。我需要检测它们是否重叠。
我从另一个问题中找到了这个案例
答案 0 :(得分:0)
这是一个简单的片段,其检查方式基于比较第一个范围的最高端到第二个范围的最低端(如果我们只考虑范围有效)。首先,分拣范围起着重要作用:
$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);
结果(包含两个重叠的日期):
Array
(
[1-9] => 8-11
[8-11] => 11-15
[11-15] => 14-20
)
答案 1 :(得分:0)
这应该涵盖所有情况:
<?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;
}