-
吃鸡游戏
代码:<?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" }}
-
泛舟湖上清波郎朗
它是简单的逻辑和增强代码<?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;}
-
当年话下
这是一个函数:<?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 ))