Remove schedules from the array if it does not satisfy a certain amount of periods required

0

I have an array with the available schedules, these times being in a 30 minute interval:

$arrHoras = ["08:30", "09:00", "09:30", "10:00", "10:30", ... , "18:30", "19:00"];

After some filters that are reserved times, I have the following array:

$arrHoras = array(
    2 => "09:00",
    3 => "09:30",
    6 => "11:00",
    7 => "11:30",
    10 => "13:00",
    11 => "13:30",
    12 => "14:00",
    13 => "14:30",
    16 => "16:00",
    17 => "16:30",
    21 => "18:30"
);

What I need is to make one more filter by removing the times that do not satisfy the amount of followed periods needed. They all serve 1 which is himself, but if it's two I need him and one more followed time, being that he can not jump, for example, from 9 to 9:30 ok, but from 9:30 to 11 no , because it skips the sequence.

If I need 2 times then the return would be this:

$arrHoras = array(
    2 => "09:00",
    6 => "11:00",
    10 => "13:00",
    11 => "13:30",
    12 => "14:00",
    16 => "16:00"
);

But if I need 3 times then the return would be this:

$arrHoras = array(
    10 => "13:00",
    11 => "13:30"
);

And if I need 4 or more times it will return an empty array.

    
asked by anonymous 19.05.2014 / 17:46

2 answers

1

Solution that I have achieved so far:

$arrHoras = array(
        2 => "09:00",
        3 => "09:30",
        6 => "11:00",
        7 => "11:30",
        10 => "13:00",
        11 => "13:30",
        12 => "14:00",
        13 => "14:30",
        16 => "16:00",
        17 => "16:30",
        21 => "18:30"
    );

$qtdeSlots = 2; // isso é variável 

$arrHorasOk = array();

for ($i=0, $c = count($arrHoras); $i < $c; $i++) {      
    $current = current($arrHoras);

    for($j = 1; $j < $qtdeSlots; $j++) $next = next($arrHoras);

    $slots = count(dateRange($current, $next, '30 minutes', 'H:i' ));
    if($slots == $qtdeSlots)
        $arrHorasOk[] = $current;

    for($k = 1; $k < $qtdeSlots-1; $k++) prev($arrHoras);

}

echo "<pre>";
var_dump($arrHorasOk);
echo "<pre>";



function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d H:i:s' )
{
    $dates   = array();
    $current = strtotime($first);
    $last    = strtotime($last);

    while( $current <= $last ) {    
        $dates[] = date($format, $current);
        $current = strtotime($step, $current);
    }
    return $dates;
}
    
19.05.2014 / 21:02
0

In order to calculate how many slots there is in the difference between one time and another, you can use the time calculations

Calculation

$d1 = new DateTime("0000-00-00 09:00:00", new DateTimeZone('America/Sao_Paulo'));
$d2 = new DateTime("0000-00-00 11:30:00", new DateTimeZone('America/Sao_Paulo'));
echo ($d1->diff($d2)->i + $d1->diff($d2)->h * 60) / 30; // retornará 5 que é o valor referente ao slot atual

From here you can browse your array and implement the rules you need. obs: Use with php 5.4 or higher.     

19.05.2014 / 20:07