我有一个以这种方式组织的小时列表:
Array (
[0] => Array (
[0] => 08:30
[1] => 09:00
[2] => 09:30
[3] => 10:00
[4] => 14:30
[5] => 15:00
[6] => 15:30
[7] => 16:00
[8] => 16:30
)
[1] => Array (
[0] => 13:30
[1] => 14:00
[2] => 14:30
[3] => 18:00
[4] => 18:30
[5] => 19:00
)
)
我试图将它们转换为这种格式:
'0': [['08:30','10:00'], ['14:30', '16:30']],
'1': [['13:30','14:30'], ['18:00', '19:00']]
jQuery插件正在使用(Day Schedule Selector)。
如果时差大于:30分钟,则范围包含在方括号之间。
我无法在PHP中找到这样的解决方案。
以下是我尝试的内容:
$prepared = '';
foreach($serialized as $day=>$hours) {
$prepared_hours = array();
foreach($hours as $hour) {
$prepared_hours[] = "['". $hour ."']";
}
$prepared .= "'{$day}' : [". implode(',', $prepared_hours) ."],\n";
}
但结果是:
'0' : [['08:30'],['09:00'],['09:30'],['10:00'],['14:30'],['15:00'],['15:30'],['16:00'],['16:30']],
'1' : [['13:30'],['14:00'],['14:30'],['18:00'],['18:30'],['19:00']
我无法定义时间范围:[' 08:30',' 10:00'],[' ..
我真的很感激任何帮助。
谢谢。
答案 0 :(得分:2)
这将为您(Demo)执行此操作:
$array=array (
0 => array (
0 => "08:30",
1 => "09:00",
2 => "09:30",
3 => "10:00",
4 => "14:30",
5 => "15:00",
6 => "15:30",
7 => "16:00",
8 => "16:30"
),
1 => array (
0 => "13:30",
1 => "14:00",
2 => "14:30",
3 => "18:00",
4 => "18:30",
5 => "19:00"
)
);
foreach($array as $index=>$times){
$prev="";
$x=-1;
foreach($times as $time){
if(!$prev || $time!=date("H:i",strtotime("+30 minutes $prev"))){
++$x;
$result[$index][$x]=array($time,$time); // store new time as start & end
}else{
$result[$index][$x][1]=$time; // update end time
}
$prev=$time;
}
}
echo "<pre>";
var_export($result);
echo "</pre>";
输出是按要求的:
array (
0 =>
array (
0 =>
array (
0 => '08:30',
1 => '10:00',
),
1 =>
array (
0 => '14:30',
1 => '16:30',
),
),
1 =>
array (
0 =>
array (
0 => '13:30',
1 => '14:30',
),
1 =>
array (
0 => '18:00',
1 => '19:00',
),
),
)
答案 1 :(得分:-1)
也许这会让你开始:
$start = new \DateTime('9:00');
$end = new \DateTime('14:00');
$period = new \DatePeriod($start,new \DateInterval('PT30M'),$end);
foreach ($period as $date) {
print $date->format('H:i') . '<br>';
}