gpt4 book ai didi

php - 如何获得时间和给定多个时间之间的间隔重叠?

转载 作者:行者123 更新时间:2023-12-02 04:52:32 25 4
gpt4 key购买 nike

我有下面的数组

 Array
(
[0] => Array
(
[from_time] => 15:00
[to_time] => 17:15
)

[1] => Array
(
[from_time] => 10:00
[to_time] => 12:15
)

[2] => Array
(
[from_time] => 09:00
[to_time] => 11:15
)

[3] => Array
(
[from_time] => 09:00
[to_time] => 11:15
)

[4] => Array
(
[from_time] => 14:00
[to_time] => 16:15
)

[5] => Array
(
[from_time] => 15:00
[to_time] => 17:15
)

)

我想在这个数组中得到共同的时间。

如果我在这个数组中找到公共(public)时间,我的预期结果应该是

Array
(
[0] => Array
(
[from_time] => 10:00
[to_time] => 11:15
)

[1] => Array
(
[from_time] => 15:00
[to_time] => 16:15
)
)

我试过下面的代码,但没有得到准确的结果。

foreach ($booking_time as $time1) {
foreach ($booking_time as $time2) {
{
if(($time1['from_time'] > $time2['from_time'] && $time1['from_time'] < $time2['to_time'])|| ( $time1['to_time'] > $time2['from_time'] && $time1['to_time'] < $time2['to_time'])){
echo $time1['from_time'];
echo $time1['to_time'];
}
}
}
}

最佳答案

快速示例(我认为它可以更短,但为了快速理解它是可以的):

$intervals = [
['from_time' => '15:00', 'to_time' => '17:15'],
['from_time' => '10:00', 'to_time' => '12:15'],
['from_time' => '09:00', 'to_time' => '11:15'],
['from_time' => '09:00', 'to_time' => '11:15'],
['from_time' => '14:00', 'to_time' => '16:15'],
['from_time' => '15:00', 'to_time' => '17:15'],
];

$overlaps = [];

foreach ($intervals as $interval) {
$key = null;
foreach ($overlaps as $_key => $_intervals) {
foreach ($_intervals as $_interval) {
if (
($_interval['from_time'] <= $interval['from_time'] && $interval['from_time'] <= $_interval['to_time'])
||
($_interval['from_time'] <= $interval['to_time'] && $interval['to_time'] <= $_interval['to_time'])
) {
$key = $_key;
break 2;
}
}
}
if (is_null($key)) {
$key = count($overlaps);
}
$overlaps[$key][] = $interval;
}
foreach ($overlaps as &$overlap) {
$from = '00:00';
$to = '23:59';
foreach ($overlap as $_interval) {
$from = max($from, $_interval['from_time']);
$to = min($to, $_interval['to_time']);
}
$overlap = ['from_time' => $from, 'to_time' => $to];
}
unset($overlap);

print_r($overlaps);

输出:

Array
(
[0] => Array
(
[from_time] => 15:00
[to_time] => 16:15
)
[1] => Array
(
[from_time] => 10:00
[to_time] => 11:15
)
)

关于php - 如何获得时间和给定多个时间之间的间隔重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18568676/

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