php - 如何在 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 中的非法字符串偏移“名称”。
提前致谢。
解决方案
您需要更改您的代码如下:
$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 键。所以你需要相应地改变你的代码。希望它可以帮助你。
推荐阅读
- c# - 我有从存储过程返回的自定义数据,所以我需要将这些数据添加到 list<> 并在 asp.net core web api c#中返回
- html - 如何使 div 粘在父容器的顶部
- python-2.7 - 为什么我收到 ImportError: No module named _gdal for GDAL in python2.7 on Amazon Linux 2
- html - 我们可以在字体真棒的关闭图标中填充颜色吗?
- react-native - React Native Appearance.addChangeListener() 什么都不做
- javascript - (index):4918 Uncaught SyntaxError: Unexpected identifier
- json - Marshal map[string] interface{} 但带有标签
- java - java - 如何使用Java中的Jbutton将双精度值传递到文本字段中?
- javascript - setInterval 一直在做错误的 if 语句
- javascript - 如何在打字稿中总结对象的属性?