2016-01-13 61 views
-1

我有一個JSON文件(如下圖),它包含多個值,這是升技這樣的 -PHP解析多個JSON數組

-makes 

    - the make 
    - the model 
     - year made 
     - year made 
     - year made 
    - the model 
     - year made 
     - year made 

    - the make 
     - the model 
     - year made 

我無法弄清楚如何通過循環每個「做」一個接一個以獲得模型和年份,到目前爲止,嘗試的每一種方式似乎都只是產生了這個品牌,而沒有其他的東西。

輸出即時尋找看起來像這樣(使用下面的代碼片段從完整的JSON文件)

am general:hummer:1998 
am general:hummer:1999 
acura:CL:1997 
acura:CL:1998 
etc.. 

JSON文件IM的小片段與合作 -

{ 
"makes": [ 
    { 
"name": "AM General", 
"models": [ 
    { 
    "name": "Hummer", 
    "years": [ 
     { 
     "year": 1998 
     }, 
     { 
     "year": 1999 
     } 
    ] 
    } 
] 
    }, 
    { 
    "name": "Acura", 
    "models": [ 
    { 
    "name": "CL", 
    "years": [ 
     { 
     "year": 1997 
     }, 
     { 
     "year": 1998 
     }, 
     { 
     "year": 1999 
     } 
    ] 
    }, 
    { 
    "name": "ILX", 
    "years": [ 
     { 
     "year": 2013 
     }, 
     { 
     "year": 2014 
     }, 
     { 
     "year": 2015 
     } 
    ] 
    }, 
    { 
    "name": "ILX Hybrid", 
    "years": [ 
     { 
     "year": 2014 
     } 
    ] 
    } 
    ] 
    } 
] 
} 
+0

你應該發佈你到目前爲止的代碼。 – jeroen

+0

是的,你做了什麼工作?你可能比你想象的更接近。 –

回答

1
$data = json_decode($json);  
foreach ($data->makes as $make) {   // assuming you have gotten this far already...   
    foreach ($make->models as $model) {  // just keep going 
     foreach ($model->years as $year) { // deeper 
      echo $make->name . ':' . $model->name . ':' . $year->year . '<br>'; 
     } 
    } 
} 
+0

感謝這工作完美:) – scriptss

0

你可以使用file_get_contents打開文件並解碼:

$file = file_get_contents('path_to_file'); 
$decoded = json_deconde($file, true); // produces array