It is possible to do what you want in the following way:
<?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);
?>
var_dump will come up with a reply like:
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
there will be an answer like:
array(2) { ["2018-03-1"]=> array(2) { [0]=> string(6) "dinner" [1]=> string(6) "snack" } ["2018-03-29"]=> array(1) { [0]=> string(6) "snack" } }
Strange, on this site Exit really finished before var_dump. On my localhost this problem did not occur. I will delete from my example :)
– David Alves
It worked right. Obg!
– Sam
@DVD in real or
var_dump
is necessary hehe. It was just an example to show the output of the array.– David Alves
Namesake, let me ask you a question: when the date is type 2018-03-1 (the day with only 1 digit) does not work... Any hint how to get around this?
– Sam
The result looks like this:
array(2) { [""]=> array(3) { [0]=> string(9) "2018-03-1" [1]=> string(6) "Jantar" [2]=> string(6) "Lanche" } ["2018-03-29"]=> array(1) { [0]=> string(6) "Lanche" } }
– Sam
See that the first item is empty
– Sam
If it is mt complicated I put in the bank with 2 digits same, same as the month
– Sam
@dvd made an edition in answer that solves your problem
– David Alves
Thanks dude Obg!
– Sam