1 回答
TA贡献1848条经验 获得超6个赞
这里你得到了算法:
对于每组时间预订,执行以下操作
找到最小的
start_time
将和
duration
之间添加到start_time
end_time
sum
查找下一个最小的时间预订
start_time
IF
current_end_time
<previous_end_time
跳转到 4 END IFIF
start_time
<previous_end_time
减去sum
END IF的差值在和
duration
之间添加start_time
end_time
跳到4,直到没有匹配的元素为止。
快乐编码:)
编辑 - 添加更干净的实现
function getSortedDays(array $days): array {
return array_map(function (array $day) {
array_multisort(array_column($day, 'start_time'), SORT_ASC, $day);
return $day;
}, $days);
}
function addTotalAttendedHours(array $days): array {
$sortedDays = getSortedDays($days);
$days = array_map(function (array $day) {
$sum = (new DateTime())->setTimestamp(0);
$previousEnd = null;
foreach ($day as $time) {
$currentStart = new DateTimeImmutable($time['start_time']);
$currentEnd = new DateTimeImmutable($time['end_time']);
if ($currentEnd < $previousEnd) continue; // this has been added
$sum->add($currentStart->diff($currentEnd));
if ($previousEnd !== null && $currentStart < $previousEnd) {
$sum->sub($currentStart->diff($previousEnd));
}
$previousEnd = $currentEnd;
}
$attendedSeconds = $sum->getTimestamp();
$day['total_attended_hours'] = sprintf(
'%02u:%02u:%02u',
$attendedSeconds / 60 / 60,
($attendedSeconds / 60) % 60,
$attendedSeconds % 60
);
return $day;
}, $sortedDays);
return $days;
}
工作示例。
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报