如何获取重叠部分时间和非重叠部分时间
时间: 2023-07-05 17:21:36 浏览: 68
如果要获取多个时间段的重叠部分和非重叠部分,可以借助上面提到的区间合并算法。具体做法如下:
1. 将所有时间段按照开始时间从早到晚排序。
2. 依次遍历每个时间段,如果这个时间段的开始时间早于前面时间段的结束时间,说明这两个时间段有重叠,可以将它们合并成一个时间段,并将这个时间段加入到重叠部分的数组中。否则,将这个时间段加入到非重叠部分的数组中。
3. 最终剩下的时间段就是不重叠的时间段。
以下是一个示例代码:
```php
function getTimeOverlap($times) {
$count = count($times);
if ($count <= 1) {
return array('overlap' => array(), 'non_overlap' => $times);
}
usort($times, function($a, $b) {
return $a['start'] - $b['start'];
});
$overlap = array();
$non_overlap = array($times[0]);
for ($i = 1; $i < $count; $i++) {
$last = end($non_overlap);
if ($times[$i]['start'] <= $last['end']) {
$last['end'] = max($last['end'], $times[$i]['end']);
$overlap[] = $last;
} else {
$non_overlap[] = $times[$i];
}
}
return array('overlap' => $overlap, 'non_overlap' => $non_overlap);
}
// 例子:
$times = array(
array('start' => strtotime('2021-01-01 08:00:00'), 'end' => strtotime('2021-01-01 10:00:00')),
array('start' => strtotime('2021-01-01 09:00:00'), 'end' => strtotime('2021-01-01 11:00:00')),
array('start' => strtotime('2021-01-01 12:00:00'), 'end' => strtotime('2021-01-01 13:00:00'))
);
$result = getTimeOverlap($times);
echo '重叠部分:';
foreach ($result['overlap'] as $time) {
echo date('Y-m-d H:i:s', $time['start']) . ' - ' . date('Y-m-d H:i:s', $time['end']) . '; ';
}
echo "\n";
echo '非重叠部分:';
foreach ($result['non_overlap'] as $time) {
echo date('Y-m-d H:i:s', $time['start']) . ' - ' . date('Y-m-d H:i:s', $time['end']) . '; ';
}
```
其中`usort`函数用于按照开始时间从早到晚排序,`$overlap`数组用于存放重叠部分的时间段,`$non_overlap`数组用于存放非重叠部分的时间段。函数`getTimeOverlap`返回一个包含重叠部分和非重叠部分的数组。