2016-07-27 18 views
1

我試圖解析一個json文件到每個循環。問題在於數據嵌套在數量遞增的容器中,這是一個問題,因爲我不能僅僅抓住每個值。我花了一段時間試圖找到一種方法來讓這個工作,我已經空了。任何想法?解析每個增量的JSON PHP

這裏是JSON文件收拾,所以你可以明白我的意思 - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json

我想獲得的值,如[數字],但我也希望得到更深層次的價值觀,如[程序] [代碼]

 <?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']; 
      } 
     ?> 
+1

json的其實並不重要。你已經解碼了它,所以它是一個普通的舊PHP數據結構,並且像任何其他PHP數據結構一樣迭代/處理它。如果你有嵌套結構,你需要多個嵌套循環。 –

+0

您正在使用'$ a變量錯誤嘗試此操作:'$ nextRaceDate = $ nextRace ['MRData'] ['RaceTable'] ['Races'] ['0'] ['Results'] [$ a]' – cmnardi

回答

0

在對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>'; 
} 

CodePad Example

+1

完美,謝謝! – Connor

0

你對你的代碼幾乎是正確的,當你嘗試$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向你展示你正在迭代你想要的東西。

0

問題是你如何訪問嵌套數組中的元素。 這裏的方式做到這一點:

$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中值的索引。

0

如果您只需要在第一場比賽的數量,試試這個辦法

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