【发布时间】:2016-12-01 22:29:00
【问题描述】:
我正在尝试将 json 文件解析为 for each 循环。问题是数据嵌套在具有递增数字的容器中,这是一个问题,因为我不能只抓取 foreach 中的每个值。我花了一段时间试图找到一种方法来让它发挥作用,但我却一无所获。有什么想法吗?
这是整理好的 json 文件,所以你可以明白我的意思 - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
我正在尝试获取诸如 [number] 之类的值,但我也想获取更深层次的值,例如 [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
【问题讨论】:
-
json 并不重要。您已经对其进行了解码,因此它是一个普通的旧 PHP 数据结构,您可以像任何其他 PHP 数据结构一样迭代/处理它。如果您有嵌套结构,则需要多个嵌套循环。
-
你使用了 '$a 变量错误试试这个:
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a ]
标签: php json loops parsing foreach