- var_dump: documentation ( source)
- date_create: documentation ( source)
- max: documentation ( source)
- min: documentation ( source)
<?php
function reduceOverlap(array $arr){
$flag = true;
while($flag){
$flag = false;
foreach($arr as $key1 => $row1){
foreach($arr as $key2 => $row2){
if($key1 === $key2) continue;
if(($row1['open'] >= $row2['open'] && $row1['open'] <= $row2['close']) OR
($row1['close'] >= $row2['open'] && $row1['close'] <= $row2['close'])){
$arr[$key1]['open'] = min($row1['open'],$row2['open']);
$arr[$key1]['close'] = max($row1['close'],$row2['close']);
unset($arr[$key2]);
$flag = true;
break 2;
}
}
}
}
return $arr;
}
function diffTotal(array $arr){
$date = date_create('1970-01-01 00:00');
foreach($arr as $row){
$diff = date_create($row['open'])->diff(date_create($row['close']));
$date->add($diff);
}
return date_create('1970-01-01 00:00')->diff($date);
}
$times = [
['open' => '2023-01-02 09:00:00', 'close' => '2023-01-02 14:00:00'],
['open' => '2023-01-02 11:00:00', 'close' => '2023-01-02 15:00:00'],
['open' => '2023-01-14 10:00:00', 'close' => '2023-01-14 11:00:00'],
];
$arr = reduceOverlap($times);
$diffTotal = diffTotal($arr);
var_dump($diffTotal);