Take the first and last date of an array

Asked

Viewed 1,647 times

4

In PHP I have this array:

$locados = array('2016-01-01', '2016-01-02', '2016-01-03', '2016-01-06', '2016-01-07', '2016-01-08');

These dates within the array represent two different rentals of an apartment:

Rental 1: 2016-01-01 until 2016-01-03

Rental 2: 2016-01-06 until 2016-01-08

My question, how do I get it with PHP, detect a group of dates and tell which is the first and which is the last.

  • I answered but, rereading again it seems that you are actually trying to split in half and make 2 groups? It has more details than exactly you need?

  • You return so from your database ? Isn’t it something like Person X rented day Y place x day y ? Post your sql or as an example of the table you take this information from

  • The reservation table even has the date of Chekin and checkout, the problem is that the customer mismanages the reservations, does not change her status, is always as a new reservation and not as a paid or confirmed reservation, then I have to use the dates of each apartment to make this control of rental periods... unfortunately.

3 answers

1


Explanation in the code comment itself

$locados = array('2016-01-01', '2016-01-02', '2016-01-03', '2016-01-06', '2016-01-07', '2016-01-08'); // Array a ser tratada

$dif = "86400"; // 1 dia em segundos (coeficiente)
$count = 0; // Inicializa contador de quantos intervalos haverá

for($i = 0; $i < count($locados); $i++) { // Laço FOR até quado existir índice na array a ser tratada
    // Função 'strtotime' converte em segundos uma data
    if((strtotime($locados[$i+1]) - strtotime($locados[$i])) == $dif) { // Calcula se uma data e a data seguinte possui interval de 1 dia (86400 segundos) 
        $resultado[$count][] = $locados[$i]; // Sendo verdadeira a condição de cima inicia nova array incluindo data
    } else {
        $resultado[$count][] = $locados[$i]; // Sendo falsa, inclui a última data do intervalo atual
        $count++; // Incrementa $count (+1) para próximo índice (intervalo) ser criado no laço
    }
}

echo "<pre>";
print_r($resultado); // Print na Array $resultado

Main function used strtotime -> Documentation: http://php.net/manual/en/function.strtotime.php

  • It wasn’t that, I need to work with the dates. Know the date periods within that array. 2016-01-01 until 2016-01-03 | 2016-01-06 until 2016-01-08 ?

  • Okay, I’m gonna correct the answer, I got it wrong.

  • takes the first and last element of the array, or only the date-based value? $primeiro = $valor[0]; $ultimo = $valor[(count($valor)-1)];

  • Caio, you really had your doubts. Regarding Rent 1 and Rent 2, how to distinguish the values related to Rent 1 and Rent 2? If that’s what I’m thinking, a two-dimensional array would solve 50% of your problem. Another thing is, detect a group of dates and tell which is the first and which last, would be the oldest and most recent date?

  • Hi, this, would be a group of dates that don’t have spaces between them, it would have to see when it has a date and even when it continues without having a date range between it, you know? ai if you have an interval, in the case of the example on 04 and 05 the system already recognizes that a first interval has formed.

  • @caiocafardo I edited my answer, I believe that this meets you, or at least it is the start to perfect the way you need.

  • That’s it! Thanks my man!

Show 2 more comments

0

If the question is sorting the data list, I would use the function usort.

She orders a array according to a comparison made by a callback.

Then see what beauty (a date has been modified to check that the ordering works):

$locados = array(
   '2016-02-01', '2016-01-02', '2016-01-03', '2016-01-06', 
   '2016-01-07', '2016-01-08'
);


usort($locados, function ($a, $b)
{
    return strtotime($a) - strtotime($b);
});


pr($locados);

The result will be:

Array
(
    [0] => 2016-01-02
    [1] => 2016-01-03
    [2] => 2016-01-06
    [3] => 2016-01-07
    [4] => 2016-01-08
    [5] => 2016-02-01
)

To take the last and first date, we can do so:

function first($arr)
{
     return reset($arr);
}


function last($arr)
{
     return end($arr);
}


first($locados); // 2016-01-02

last($locados); // 2016-02-01

If you don’t understand why to create new functions to get the last and first element, I suggest you read this answer:

/a/89003/4995

0

Simple and clean:

<?php

    $array = array('2016-01-01', '2016-01-02', '2016-01-03', '2016-01-06', '2016-01-07', '2016-01-08');

    foreach ($array as $element) 
    {
        if ($element === reset($array))
            $minimo = $element;

        if ($element === end($array))
            $maximo = $element;
    }
?>

    Aluguel 1: <?=$minimo?> até <?=$maximo ?>

Browser other questions tagged

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