Search code examples
phparraystimemergedate-range

Combine 2 arrays with time strings to 1 array of time ranges


I have 2 arrays and I'd like to group them into one array:

$arrayA = Array
    (
        [0] => 08:00am
        [1] => 10:00am
        [2] => 12:00pm
        [3] => 02:00pm
        [4] => 04:00pm
        [5] => 06:00pm
        [6] => 08:00pm
        [7] => 10:00pm
    )

$arrayB = Array
    (
        [0] => 09:00am
        [1] => 11:00am
        [2] => 01:00pm
        [3] => 03:00pm
        [4] => 05:00pm
        [5] => 07:00pm
        [6] => 09:00pm
    )

I tried:

  foreach ($arrayA as $keeyy=>$val)
  {
      $arrC[] = $val." "."to"." ".$$arrayB[$keeyy];
  }

but my result was:

<b>Notice</b>:  Undefined offset: 7 in <b>C:\Users\user\Desktop\xammp\htdocs\Ea....on line <b>104</b><br />
Array
    (
        [0] => 08:00am to 09:00am
        [1] => 10:00am to 11:00am
        [2] => 12:00pm to 01:00pm
        [3] => 02:00pm to 03:00pm
        [4] => 04:00pm to 05:00pm
        [5] => 06:00pm to 07:00pm
        [6] => 08:00pm to 09:00pm
        [7] => 10:00pm to 
    )

What I want to achieve is:

Array
(
    [0] => 8:00am To 09:00am  
    [1] =>09:00am To 10:00am
    [2] =>10:00am To 11:00am
    [3] => 11:00am To 12:00pm
    [4] => 12:00pm To 1:00pm
    [5] => 1:00pm To 2:00pm
    [6] => 2:00pm To 3:00pm
    [7] => 3:00pm To 4:00pm
    [8] => 4:00pm To 5:00pm
    [9] => 5:00pm To 6:00pm
    [10] => 6:00pm To 7:00pm
    [11] => 7:00pm To 8:00pm
    [12] => 8:00pm To 9:00pm
    [13] => 9:00pm To 10:00pm
)

Solution

  • You can merge the arrays and map them to a timestamp and sort ascending. Then just loop and get the current time and the next one based on key if it exists:

    $all = array_merge($one, $two);
    array_multisort(array_map('strtotime', $all), $all);
    
    foreach($all as $key => $time) {
        if(isset($all[$key + 1])) {
            $result[] = "$time To {$all[$key + 1]}";
        }
    }
    

    If they are already in order, the first array is the beginning, and they have the same count, then loop and use the key to get the end and save it for the beginning of the next:

    foreach($one as $key => $time) {
        if(isset($prev)) {
            $result[] = "$prev To $time";
        }
        $prev = $two[$key];
        $result[] = "$time To $prev";
    }