Valid schedules

1

I have array with several times, sometimes having only 4 and sometimes N times.

I need to get only a few records.

Follow my code:

$array = array(
      0  => "08:00:00",
      1  => "08:02:00",
      2  => "08:04:00",
      3  => "08:08:00",
      4  => "08:10:00",
      5  => "10:59:00",
      6  => "11:00:00",
      7  => "11:05:00",
      8  => "11:11:00",
      9  => "13:00:00",
      10 => "13:03:00",
      11 => "13:06:00",
      12 => "13:08:00",
      13 => "18:00:00",
      14 => "18:03:00",
      15 => "18:06:00",
      16 => "18:35:00",
      17 => "19:15:00"
);

$auxiliar = null;
foreach ($registros as $indice => $registro) {
    if ($auxiliar === null) {
        $auxiliar = $registro;
        continue;
    }

    $registroAtual   = current($registros); //Registro atual
    $proximoRegistro = next($registros);    //Proximo registro

    //Tem um proximo registro
    if($proximoRegistro){
      //Diferença entre dois horários
      $diffHorarios = $this->calculaTempo($registroAtual, $proximoRegistro);

      //Houve registros no intervalo de 10 minutos
      if($diffHorarios <= '00:10:00'){
        unset($registros[$indice]);
      }
    }
  }
    
asked by anonymous 21.09.2016 / 20:21

1 answer

1

When you use data of the Data type, always use the DateTime class and the DateInterval class :

$array = array(
    0  => "08:00:00", 1  => "08:02:00", 2  => "08:04:00", 3  => "08:08:00",
    4  => "08:10:00", 5  => "10:59:00", 6  => "11:00:00", 7  => "11:05:00",
    8  => "11:11:00", 9  => "13:00:00", 10 => "13:03:00", 11 => "13:06:00",
    12 => "13:08:00", 13 => "18:00:00", 14 => "18:03:00", 15 => "18:06:00",
    16 => "18:35:00", 17 => "19:15:00");

function result_time_array(array $values)
{
    $index = 0;
    $c = date_create_from_format('H:i:s', $values[0]);
    $agr[$index][] = $values[0];
    for ($i = 1; $i < count($values); $i++)
    {
        $d = date_create_from_format('H:i:s', $values[$i]);
        $diff = $c->diff($d);
        if (!($diff->i <= 10 && $diff->h === 0))
        {
            $index++;
        }
        $c = date_create_from_format('H:i:s', $values[$i]);
        $agr[$index][] = $values[$i];
    }
    $st = 'e';
    $index = 0;
    foreach ($agr as $key => $value)
    {
        if ($st === 'e')
        {
            $result[$index][$st] = $value[0];
            $st = 's';
        }
        else if ($st === 's')
        {
            $result[$index][$st] = end($value);
            $st = 'e';
            $index++;
        }
    }
    return $result;
}

var_dump(result_time_array($array));

Exit:

array(3) {
  [0]=>
  array(2) {
    ["e"]=>
    string(8) "08:00:00"
    ["s"]=>
    string(8) "11:11:00"
  }
  [1]=>
  array(2) {
    ["e"]=>
    string(8) "13:00:00"
    ["s"]=>
    string(8) "18:06:00"
  }
  [2]=>
  array(2) {
    ["e"]=>
    string(8) "18:35:00"
    ["s"]=>
    string(8) "19:15:00"
  }
}

PHP Sandbox

    
21.09.2016 / 22:38