首页 > 解决方案 > 如何在 json 文件的第一个对象中限制 foreach

问题描述

您好我正在尝试将 json 文件打印到表格中。json 文件来自这个网站https://jsonvat.com/。我想打印$data->rates->periods->rates[0]->standard。但我明白了

“不能在 ... 中使用 stdClass 类型的对象作为数组”

我的代码是这样的:

$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>';

当我更改$data = json_decode($response);$data = json_decode($response, true);并且代码变为

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

我收到一条错误消息

警告:第 23 行 C:\xampp\htdocs\wordpress\wp-content\plugins\test-plug\functions.php 中的非法字符串偏移“名称”。

提前致谢。

标签: phpjson

解决方案


您需要更改您的代码如下:

$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>';

在这里,我发现 Rate 键中有时不存在 reduce 或 super_reduced 键。所以你需要相应地改变你的代码。希望它可以帮助你。


推荐阅读