How to take data from within a foreach array in php

Asked

Viewed 52 times

0

I am receiving data from a registration form. One of these data is an array... inserir a descrição da imagem aqui

And this array of objects, (Dates), can have numerous positions/quantities. In the image above, I tested with these 2. I’m trying to do a foreach to get the data that comes in the Dates array, however, I’m not getting it.

With that code:

$dates = $data->dates;
print_r($dates);

foreach($dates as $key){
    echo $day = $key->date;
}

and I’m only able to display the dates and united

11/06/202112/06/2021

I need to separate the data as follows:

inserir a descrição da imagem aqui

How can I do that? I’ve been told to use two foreachs, but I’m not making it. From now on, thank you.

2 answers

1


Hello! I managed to run calling the reference by Brackets

$i = 1;
foreach($dates as $key){
    echo 'data_' . $i . '&nbsp' . $key->date . '<br>';
    echo 'quantidade_'. $i . '&nbsp' . $key->quantity . '<br>'; 
    echo 'valor_'. $i . '&nbsp' . $key->value. '<br>';
    echo '<br>';
    $i++;
}
//saida
//data_1 11/06/2021
//quantidade_1 2
//valor_1 100
//
//data_2 12/06/2021
//quantidade_2 2
//valor_2 150
  • I’ll try, thanks Jhonata.

  • I ran the lines and gave this: "<b>Fatal error</b>: Uncaught Error: Cannot use Object of type stdClass as array in /Applications/MAMP/htdocs/Projects/Web/eudirijo/api/rentcars/Availability.php:29" The 29 line is this below echo 'data_' . $i . '&nbsp' . $key['date'] . '<br>'

  • Hello, I edited the code, at the time of testing I created arrays instead of Obj. I think now will work in your code! Sorry for the glitch.

-2

You can transform the objects within the array into an array and then run the foreach

//Transforma os Object dentro do Array em Array
$tudoArray = json_decode(json_encode($data->dates), true);

//translation
$k_trans = array(
    'date'      => 'Data',
    'value'     => 'Valor',
    'quantity'  => 'Quantidade',
);

$i = 0;
foreach($tudoArray as $values1){
    $i++;
    foreach($values1 as $key => $value2){
        echo "{$k_trans[$key]}_{$i} {$value2}<br>";
    }
    echo '<br>';
}

Browser other questions tagged

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