Create a start and end period with a list of days

Asked

Viewed 808 times

0

I have an array of days and 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

Should generate an array the periods '01/02/2015 to 05/02/2015' and '09/02/2015 to 12/02/2015', because on these dates, the days are consecutive, there is no break.

That’s the code I have so far, but I’m already lost, tired head and I can’t think anymore.

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

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 Function?

1 answer

0


I didn’t understand it very well. You want to separate the dates when the difference of days is greater than "1" is this?

If it is I did this function see if it meets you: (http://ideone.com/0B7hCC)

<?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);
  • Perfect, Adir! Thank you very much, I was already getting discouraged with the creation of this code :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.