Mount a two-dimensional array from another array

4

I have the array $dados below:

array(5) {
   [0]=> "2018-03-28"
   [1]=> "jantar"
   [2]=> "lanche"
   [3]=> "2018-03-29"
   [4]=> "lanche"
}

From this array, how could I mount another two-dimensional array so that it looks like this:

$dados1 = array(
   '2018-03-28' => array('jantar','lanche'),
   '2018-03-29' => array('lanche')
);

Note that each item in the form of date should create a new array inside $dados1 and this array will contain the subsequent items until the next date .

As I do not know how to mount this type of array with PHP, I could not think of a way to do that.

    
asked by anonymous 27.03.2018 / 21:48

1 answer

3

You can do this yourself, as follows:

<?php
// Seu array inicial
$array = array("2018-03-28", "jantar", "lanche","2018-03-29", "lanche");

// Declaração do array final e variável auxiliar de data
$dados1 = array();
$data_atual = null;

foreach ($array as $key => $value) {
    // Verifica se o $value é uma data
    if (date('Y-m-d', strtotime($value)) == $value) {
        // Salva qual a data atual para o array bidimensional
        $data_atual = $value;
    }else{
        // Adiciona o tipo de refeição na data atual
        $dados1[$data_atual][] = $value;
    }
}

var_dump($dados1);
?>

The var_dump will output a response of type:

  

array (2) {["2018-03-28"] = > array (2) {[0] = > string (6) "dinner" [1] = > string (6) "snack"} ["2018-03-29"] = > array (1) {[0] = > string (6) "snack"}}

Edit for date cases in "2018-03-1" format:

<?php 
$array = array("2018-03-1", "jantar", "lanche","2018-03-29", "lanche");

$dados1 = array();
$data_atual = null;

foreach ($array as $key => $value) {
    $data1 = date('Y-m-d', strtotime($value));
    $data2 = $value;

    // Verifica se o $value é uma data
    if (strtotime($data1) == strtotime($data2)) {
        $data_atual = $value;
    }else{
        $dados1[$data_atual][] = $value;
    }
}

var_dump($dados1);
?>

The var_dump will output a response of type:

  

array (2) {["2018-03-1"] = > array (2) {[0] = > string (6) "dinner" [1] = > string (6) "snack"} ["2018-03-29"] = > array (1) {[0] = > string (6) "snack"}}

    
27.03.2018 / 21:57