我有多个JSON API网址,我正试图从中提取数据。它们的结构都相同,但来自不同位置的数据。我正在尝试获取每个文件并在表中回显它们中的数据。当我只是分别从每个文件中提取数据并为每个TR重复代码时,我设法让它工作,但是我试图让它以像从MySQL中提取数据行的方式循环数据库,因此它将在前端显示来自表格的单独行中每个位置的数据。
JSON文件结构
"newval": {
"website": {
"url": "abc.com"
},
"versions": {
"version1": {
"website": {
"url": "abc.com"
}
},
"version2": {
"website": {
"url": "def.com"
}
}
}
我已经设法通过以下代码将其用于一个工作站:
{
"Altimeter": "3005",
"Flight-Rules": "VFR",
"Raw-Report": "KJFK 241851Z 19009KT 10SM CLR 31/18 A3005 RMK AO2 SLP174 T03060183",
"Station": "KJFK",
"Visibility": "10",
"Wind-Direction": "190",
"Wind-Gust": "",
"Wind-Speed": "09",
}
我希望从两个站点收集数据并输出如下所示
<?
$json = file_get_contents('Station_1_URL');
$decoded = json_decode($json, true);
?>
<table>
<tbody>
<tr>
<td><? echo $decoded['Station']; ?></td>
<td><? echo $decoded['Flight-Rules']; ?></td>
<td><? echo $decoded['Wind-Direction']; ?> @ <? echo $decoded['Wind-Speed']; ?></td>
<td><? echo $decoded['Altimeter']; ?></td>
</tr>
</tbody>
</table>
答案 0 :(得分:0)
创建一个列表,列出您需要遍历的所有站点URL并在foreach
循环中包装前端:
<?php
$station_urls = ['Station_1_URL', 'Station_2_URL', 'Station_3_URL'];
?>
<table>
<tbody>
<? foreach ($station_urls as $station_url) :
$json = file_get_contents($station_url);
$decoded = json_decode($json, true);
?>
<tr>
<td><? echo $decoded['Station']; ?></td>
<td><? echo $decoded['Flight-Rules']; ?></td>
<td><? echo $decoded['Wind-Direction']; ?> @ <? echo $decoded['Wind-Speed']; ?></td>
<td><? echo $decoded['Altimeter']; ?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
答案 1 :(得分:0)
将您的电台网址放入数组
<?php
$stationURLs = array(Station_1_URL, Station_2_URL, ...);
foreach ($stationURLs as $stationURL) {
// fetch the JSON response
// print the <tr>
// (same as your chunk of code for station1)
}
?>