Skip to content
Advertisement

How to limit foreach in the first object of a json file

Hello I am trying to print a json file to a table. The json file is from this website https://jsonvat.com/. I want to print $data->rates->periods->rates[0]->standard. But I get

“Cannot use object of type stdClass as array in …”

My code is this:

$data = json_decode($response);


echo '<table class="table"><thead><tr><th scope="col">Country</th><th scope="col">First</th><th scope="col">Last</th><th scope="col">Handle</th></tr></thead><tbody>';
foreach($data->rates as $rate){
    echo '<tr><th scope="row">'.$rate->name.'</th>';
    foreach($rate->periods as $period){
    echo '<td>'.$period->rates->standard.'</td><td>'.$period->rates->redused.'</td><td>'.$period->rates->super_reduced.'</td></tr>';
    }
}
echo '</tbody></table>';

When I change $data = json_decode($response); to $data = json_decode($response, true); and the code becomes

foreach($data as $rate){
        echo '<tr><th scope="row">'.$rate['name'].'</th>';

I get an error saying

Warning: Illegal string offset ‘name’ in C:xampphtdocswordpresswp-contentpluginstest-plugfunctions.php on line 23.

Thanks in advance.

Advertisement

Answer

You need to change your code as below:

$json = file_get_contents("https://jsonvat.com/");
$dataObject = json_decode($json, true);

echo '<table class="table"><thead><tr><th scope="col">Country</th><th scope="col">First</th><th scope="col">Last</th><th scope="col">Handle</th></tr></thead><tbody>';
foreach($dataObject['rates'] as $rate){
    echo '<tr><th scope="row">'.$rate['name'].'</th>';
    foreach($rate['periods'] as $period){
    echo '<td>'.$period['rates']['standard'].'</td><td>'.$period['rates']['reduced'].'</td><td>'.$period['rates']['super_reduced'].'</td></tr>';
    }
}
echo '</tbody></table>';

Here, I found that sometime reduced or super_reduced key does not exist in Rate key. so you need to make your code changes accordingly. Hope it helps you.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement