假设我们有一个“较大的”日期和时间范围,例如
$big = [
'start' => '2018-09-01 00:00:00',
'stop' => '2018-09-01 23:59:59'
]
我必须创建一个数组,其所有范围都未包含在另一个数组中,如下所示:
$exclude = [
[
'start' => '2018-09-01 12:00:00',
'stop' => '2018-09-01 14:59:59'
],
[
'start' => '2018-09-01 18:00:00',
'stop' => '2018-09-01 19:59:59'
]
]
以使结果结构如下所示:
$results = [
[
'start' => '2018-09-01 00:00:00',
'stop' => '2018-09-01 11:59:59'
],
[
'start' => '2018-09-01 15:00:00',
'stop' => '2018-09-01 17:59:59'
],
[
'start' => '2018-09-01 20:00:00',
'stop' => '2018-09-01 23:59:59'
]
]
tl; dr
我有一个很大的日期时间范围(就像上面写的那样),我必须通过删除来自另一个结构的一个或多个范围来创建一个结果日期范围。诸如提取工作之类的工作从一天开始就中断了,因此仅保留了实际的工作时间。
我正在使用Carbon和Laravel,对此有任何本地解决方案,还是我应该解析整个结构并自行打个孔?我不想重新发明轮子。
答案 0 :(得分:0)
我对Carbon不太了解,但是我知道Carbon扩展了本机DateTime类,因此可以修改以下代码来实现您的目的:
$result=[['start'=>$big['start'],'stop'=>''],['start'=>'','stop'=>''],['start'=>'','stop'=>$big['stop']]];//you can build this with a loop if you want...
foreach($result as $k =>$value){
switch($k){
case 0:
$result[$k]['stop']=(($date=date_create($exclude[0]['start']))&&$date->sub(new dateInterval('PT1S')))?$date->format('Y-m-d H:i:s'):'';
unset($date);
break;
case 1:
$result[$k]['start']=(($date=date_create($exclude[0]['stop']))&&$date->add(new dateInterval('PT1S')))?$date->format('Y-m-d H:i:s'):'';
$result[$k]['stop']=(($date=date_create($exclude[1]['start']))&&$date->sub(new dateInterval('PT1S')))?$date->format('Y-m-d H:i:s'):'';
unset($date);
break;
case 2:
$result[$k]['start']=(($date=date_create($exclude[1]['stop']))&&$date->add(new dateInterval('PT1S')))?$date->format('Y-m-d H:i:s'):'';
unset($date);
break;
default:
break;
}
}