基于值对数组进行分组

时间:2017-01-24 06:52:17

标签: php arrays

我想分组数组值 我的数组看起来像下面30分钟的时间间隔

$arr = ["00:00","00:30","01:00","01:30","02:00","02:30","03:00","04:30","05:00","05:30"];

我希望输出像

Array ( [0] => Array ( [0] => 00:00 [1] => 03:00 ),[1]=> Array ( [0] => 04:30 [1] => 05:30 )) ;

这是我实现结果的代码

$output = array();
$start = $arr[0];
for($i=1; $i<count($arr); $i++) {
    if($i == count($arr)-1) {
        $interval = array($start,$arr[$i]);
        array_push($output,$interval);
        break;
    }
    if((int)($arr[$i]) - (int)($arr[$i-1]) > 1) {
        $interval = array($start,$arr[$i-1]);
        array_push($output,$interval);
        $start = $arr[$i];
    }
}
print_r($output);

但我的结果看起来像

Array ( [0] => Array ( [0] => 00:00 [1] => 05:30 ) ) 

由于

1 个答案:

答案 0 :(得分:1)

$times = ["00:00","00:30","01:00","01:30","02:00","02:30","03:00","04:30","05:00","05:30"];

$result = array();

$index = 0;
for ($i=0; $i < count($times); $i++){
    if($i == 0){
        $result[$index][] = $times[$i];
    }elseif($i == count($times)-1){
        $result[$index][] = $times[$i];
    }else{
        if((h2m($times[$i])-h2m($times[$i-1])) > 30){
            $result[$index][] = $times[$i-1];
            $index++;
            $result[$index][] = $times[$i];
        }
    }
}

var_dump($result);


FUNCTION h2m($hours) {
    $t = EXPLODE(":", $hours);
    $h = $t[0];
    IF (ISSET($t[1])) {
        $m = $t[1];
    } ELSE {
        $m = "00";
    }
    $mm = ($h * 60) + $t[1];
    RETURN $mm;
}