Home > Net >  How to group time in array
How to group time in array

Time:01-06

I have the following array in PHP:

$time = array("09:00AM","09:05AM","09:10AM","09:15AM","09:20AM","09:30AM","12:15PM", "12:20PM", "12:25PM","15:30PM","15:35PM","15:40AM","15:45AM","15:50PM");

How can I echo the following format? Does anyone know if this is possible?

09:00AM - 09:30AM
12:15PM - 12:25PM
15:30PM - 15:50PM

My understanding of array still need practicing.

I tried to search for a solution but did not find anywhere that did this

CodePudding user response:

Sorry this is my updated script: $time = array("09:00","09:05","09:10","09:15","09:20","09:30","12:15", "12:20", "12:25","15:30","15:35","15:40","15:45","15:50"); ...

Based on the above (your last comment) you can get the following result:

09:00 -- 09:30
12:15 -- 12:25
15:30 -- 15:50

The code for that in detail:

<?php

$time = Array(
            "09:00","09:05","09:10","09:15","09:20","09:30",
            "12:15", "12:20", "12:25",
            "15:30","15:35","15:40","15:45","15:50"
);

$map = Array();
$prev = "";

foreach ($time as $t) {
    $dt = date_create_from_format("H:i", $t);
    $hr = date_format($dt,"H");
    $mi = date_format($dt,"i");
    if ($prev !== $hr) {
        $map[$hr] = Array($mi);
        $prev = $hr;
    }
    else {
        $map[$hr][] = $mi;
    }   
}

foreach ($map as $k => $v) {
    // sort($v); // this is optional
    $first = $v[0];
    $last = $v[count($v) - 1];
    echo "$k:$first -- $k:$last" . "<br>";
}

?>

Note that this code can possibly be refined to be concise.

  • Related