Create a start and end period with a list of days

0

I have an array of days and I need to create periods based on it.

For example this array

01/02/2015
02/02/2015
03/02/2015
04/02/2015
05/02/2015
09/02/2015
10/02/2015
11/02/2015
12/02/2015

Arrange the periods '01 / 02/2015 to 05/02/2015 'and '09 / 02/2015 to 12/02/2015', because on those dates, the days are consecutive, there is no break.

This is code I have so far, but I'm already lost, my head is tired and I can not think anymore.

The idea is to take the first day (the array of days is guaranteed chronologically) and calculate the difference of timestamp by progressing one unit (distance) at a time. If the difference is greater, get the first and last that worked out.

86400 é 24*60*60

function processaDias($arrDias) {

    $retorno = array();


    $limiteInferior = $arrDias[0];
    $distancia = 1;

    for($i = 1; $i < count($arrDias); $i++) {

        $atualTeste = $arrDias[$i];



        //calcular dif dias
        list($d1, $m1, $a1) = explode("/", $limiteInferior);
        list($d2, $m2, $a2) = explode("/", $atualTeste);

        $startTimeStamp = strtotime($a1."/".$m1."/".$d1);
        $endTimeStamp = strtotime($a2."/".$m2."/".$d2);

        $timeDiff = ($endTimeStamp - $startTimeStamp);

        if($timeDiff == 86400*$distancia) {


            $limiteSuperior = $atualTeste;
            $distancia++;

        } else {

            $retorno[] = $limiteInferior." a ".$arrDias[$i-1];
            $limiteInferior = $atualTeste;
            $distancia = 1;
        }

        var_dump($retorno);
    }

What should I modify to complete the function?

    
asked by anonymous 22.04.2015 / 21:31

1 answer

0

I did not quite understand. Do you want to separate the dates when the difference in days is greater than "1"?

If you did this function, see if it suits you: ( link )

<?php

$arr = [
    "01/02/2015",
    "02/02/2015",
    "03/02/2015",
    "04/02/2015",
    "05/02/2015",
    "09/02/2015",
    "10/02/2015",
    "11/02/2015",
    "12/02/2015",
];

//complexidade O(n)
function processaDias($arrDias) {
    $index = 0;
    $dia_anterior = "";
    $ret = [];
    foreach($arrDias as $dia) {
        if ($dia_anterior === "") {
            $ret[$index][] = $dia;
            $dia_anterior = $dia;
            continue;
        }

        $d1 = DateTime::createFromFormat("d/m/Y", $dia_anterior);
        $d2 = DateTime::createFromFormat("d/m/Y", $dia);

        $diff = $d2->diff($d1);

        if($diff->format("%d") !== "1") {
            $index++;
        }

        $ret[$index][] = $dia;

        $dia_anterior = $dia;
    }

    return $ret;
}

$res = processaDias($arr);

var_dump($res);
    
22.04.2015 / 22:34