gpt4 book ai didi

PHP 确定多个(n)日期时间范围何时相互重叠

转载 作者:可可西里 更新时间:2023-11-01 12:54:04 26 4
gpt4 key购买 nike

我正在努力解决以下问题:

这是一个日历程序,给定一组来自​​多个人的可用日期时间集,我需要弄清楚每个人在 PHP 中可用的日期时间范围

可用性集:

p1: start: "2016-04-30 12:00", end: "2016-05-01 03:00"

p2: start: "2016-04-30 03:00", end: "2016-05-01 03:00"

p3: start: "2016-04-30 03:00", end: "2016-04-30 13:31"
start: "2016-04-30 15:26", end: "2016-05-01 03:00"

我正在寻找一个我可以调用的函数,它将告诉我所有 (p) 人同时可用的日期时间范围。

在上面的例子中,答案应该是:

2016-04-30 12:00 -> 2016-04-30 13:31
2016-04-30 15:26 -> 2016-05-01 03:00

我确实找到了这个类似的问题和答案 Datetime -Determine whether multiple(n) datetime ranges overlap each other in R

但我不知道那是什么语言,也无法翻译答案中的逻辑。

最佳答案

那很有趣。可能有一种比每分钟循环一次更优雅的方法,但我不知道 PHP 是否适合它。请注意,这目前需要管理开始和结束时间以分别搜索,尽管根据可用类次计算它们相当简单。

<?php
$availability = [
'Alex' => [
[
'start' => new DateTime('2016-04-30 12:00'),
'end' => new DateTime('2016-05-01 03:00'),
],
],

'Ben' => [
[
'start' => new DateTime('2016-04-30 03:00'),
'end' => new DateTime('2016-05-01 03:00'),
],
],

'Chris' => [
[
'start' => new DateTime('2016-04-30 03:00'),
'end' => new DateTime('2016-04-30 13:31')
],

[
'start' => new DateTime('2016-04-30 15:26'),
'end' => new DateTime('2016-05-01 03:00')
],
],
];

$start = new DateTime('2016-04-30 00:00');
$end = new DateTime('2016-05-01 23:59');
$tick = DateInterval::createFromDateString('1 minute');

$period = new DatePeriod($start, $tick, $end);

$overlaps = [];
$overlapStart = $overlapUntil = null;

foreach ($period as $minute)
{
$peopleAvailable = 0;

// Find out how many people are available for the current minute
foreach ($availability as $name => $shifts)
{
foreach ($shifts as $shift)
{
if ($shift['start'] <= $minute && $shift['end'] >= $minute)
{
// If any shift matches, this person is available
$peopleAvailable++;
break;
}
}
}

// If everyone is available...
if ($peopleAvailable == count($availability))
{
// ... either start a new period...
if (!$overlapStart)
{
$overlapStart = $minute;
}

// ... or track an existing one
else
{
$overlapUntil = $minute;
}
}

// If not and we were previously in a period of overlap, end it
elseif ($overlapStart)
{
$overlaps[] = [
'start' => $overlapStart,
'end' => $overlapUntil,
];

$overlapStart = null;
}
}

foreach ($overlaps as $overlap)
{
echo $overlap['start']->format('Y-m-d H:i:s'), ' -> ', $overlap['end']->format('Y-m-d H:i:s'), PHP_EOL;
}

关于PHP 确定多个(n)日期时间范围何时相互重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36868675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com