[英]Parsing JSON in for each with increment PHP
我正在嘗試將json文件解析為每個循環。 問題是數據嵌套在具有遞增數字的容器中,這是一個問題,因為我不能只獲取foreach中的每個值。 我花了一段時間試圖找到一種方法讓這個工作,我已經空了。 任何想法?
這是整理的json文件,所以你可以看到我的意思 - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
我想獲得[數字]等值,但我也希望獲得更深層的值,例如[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'];
}
?>
你的代碼幾乎是正確的,當你嘗試$a++
時,你做錯$a++
。 刪除$a = 0
,您將不需要它。
直到這里你是對的
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
你接下來要做的就是這個
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
所以,在我的代碼中,你停止在Results
,然后,你想迭代所有的結果,從0到X,第一個foreach
將這樣做,你必須訪問$value
。 因此,添加另一個foreach
來迭代$value
具有的所有內容。
你去了,我添加了一個print_r
來向你展示你正在迭代你想要的東西。
問題是如何訪問嵌套數組中的元素。 這是一種方法:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
我不知道你的對象來自哪里,但是,如果你確定你每次都會得到一場比賽,那么可以抑制第一個循環並使用快捷方式:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
您的問題是索引必須是整數,因為該數組是非關聯的。 給一個字符串,php正在尋找鍵'$ a ++',而不是$ a中的值的索引。
如果您只需要第一場比賽的號碼,請嘗試這種方式
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
也許你需要迭代'種族'屬性如果你需要所有,請嘗試這種方式:
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}
在解碼json
,不需要將對象展平為關聯array
。 只需使用它應該如何使用它。
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.