Используя идею, предложенную Андре в ответе выше, я мог бы достичь цели с помощью кода ниже:
Примечание: для правильной работы не забудьте упорядочить время по времени старта ASC
<?php
// Function to sum times
function sum($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time) {
list($hour, $minute, $second) = explode(':', $time);
$seconds += $hour * 3600;
$seconds += $minute * 60;
$seconds += $second;
}
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
// Function to subtract times
function sub($end, $start) {
$end = strtotime($end);
$start = strtotime($start);
$seconds = $end - $start;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
// Some values to work on
// To get this working the times should be ordered by start time ASC
$start = array(
'11:00:00',
'13:00:00',
'14:00:00',
'15:00:00',
);
$end = array(
'12:30:00',
'14:30:00',
'16:00:00',
'16:30:00',
);
$total = "00:00:00";
$tmp = "00:00:00";
for ($i = 0; $i <= count($start); $i++) {
$start_t = $start[$i];
$end_t = $end[$i];
if ($start_t >= $tmp) {
$total = sum(sub($end_t, $start_t), $total);
$tmp = $end_t;
} else {
if ($end_t > $tmp) {
$total = sum(sub($end_t, $tmp), $total);
$tmp = $end_t;
} else {
}
}
}
echo $total;