3 回答
TA贡献1829条经验 获得超7个赞
代码:
<?php
$times = [
'12:00am',
'12:15am',
'12:30am',
'12:45am',
'1:00am',
'1:15am',
'1:30am',
'1:45am',
'2:00am',
'3:15am',
'3:30am',
'3:45am',
'4:00am',
'1:00pm',
'1:15pm',
'1:30pm'
];
$previous = null;
$results = [[]];
foreach ($times as $time) {
if (
$previous === null ||
(new \DateTime())->createFromFormat('h:ia', $time)->getTimestamp() -
(new \DateTime())->createFromFormat('h:ia', $previous)->getTimestamp() === 15*60
) {
$index = count($results)-1;
} else {
$index = count($results);
}
$results[$index][] = $time;
$previous = $time;
}
echo "<pre>";
var_dump($results);
echo "</pre>";
输出(html 视图):
array(3) {
[0]=>
array(9) {
[0]=>
string(7) "12:00am"
[1]=>
string(7) "12:15am"
[2]=>
string(7) "12:30am"
[3]=>
string(7) "12:45am"
[4]=>
string(6) "1:00am"
[5]=>
string(6) "1:15am"
[6]=>
string(6) "1:30am"
[7]=>
string(6) "1:45am"
[8]=>
string(6) "2:00am"
}
[1]=>
array(4) {
[0]=>
string(6) "3:15am"
[1]=>
string(6) "3:30am"
[2]=>
string(6) "3:45am"
[3]=>
string(6) "4:00am"
}
[2]=>
array(3) {
[0]=>
string(6) "1:00pm"
[1]=>
string(6) "1:15pm"
[2]=>
string(6) "1:30pm"
}
}
TA贡献1818条经验 获得超3个赞
它是简单的逻辑和增强代码
<?php
$input = Array
(
"12:00am",
"12:15am",
"12:30am",
"12:45am",
"1:00am",
"1:15am",
"1:30am",
"1:45am",
"2:00am",
"3:15am",
"3:30am",
"3:45am",
"4:00am",
"1:00pm",
"1:15pm",
"1:30pm",
);
$periods = [];
foreach($input as $time) {
$hour = substr($time, 0, strpos($time, ':'));
$partOfDay= substr($time, strlen($time) - 2);
$index = ($hour== "12") ? "0" : floor($hour/2.00001);
$periods[$index.":".$partOfDay][] = $time;
}
echo "<pre>";
var_dump($periods);
echo "</pre>";
exit();
?>
已编辑
根据OP的逻辑,我简化了逻辑,这是代码。
$periods = array();
$index = 0;
$old_value = 0;
foreach($input as $time) {
//converting time to minutes
$new_value = (intval(date("H",strtotime($time)))*60) + intval(date("i",strtotime($time)));
if($new_value > ($old_value+15)){
$index++;
}
$periods[$index][] = $time;
$old_value = $new_value;
}
TA贡献1890条经验 获得超9个赞
这是一个函数:
<?php
$input = [
"12:00am",
"12:15am",
"12:30am",
"12:45am",
"1:00am",
"1:15am",
"1:30am",
"1:45am",
"2:00am",
// gap here
"3:15am",
"3:30am",
"3:45am",
"4:00am",
// gap here
"1:00pm",
"1:15pm",
"1:30pm",
];
$period = 15;
$result = split_periods($input, $period);
var_dump($result);
function split_periods($times, $period) {
$standard_diff = $period * 60;
$separated = [];
$last_time = null;
$n = 0;
foreach ($times as $time) {
$current_time = strtotime($time);
if ($last_time) {
$diff = $current_time - $last_time;
if ($diff != $standard_diff) {
++$n;
}
}
$separated[$n][] = $time;
$last_time = $current_time;
}
return $separated;
}
为函数提供时间数组,以及预期的时间间隔(以分钟为单位)。它返回一个数组数组,如下所示。
Array
(
[0] => Array
(
[0] => 12:00am
[1] => 12:15am
[2] => 12:30am
[3] => 12:45am
[4] => 1:00am
[5] => 1:15am
[6] => 1:30am
[7] => 1:45am
[8] => 2:00am
)
[1] => Array
(
[0] => 3:15am
[1] => 3:30am
[2] => 3:45am
[3] => 4:00am
)
[2] => Array
(
[0] => 1:00pm
[1] => 1:15pm
[2] => 1:30pm
)
)
- 3 回答
- 0 关注
- 201 浏览
添加回答
举报