我有以下json對象在php中解析。解析多級JSON對象/數組
我似乎無法循環瀏覽json以便一次獲取所有這些屬性,看起來像下面的示例。
list->dt_txt
例如。 20170308 list->weather->main
例如。雨 city->name
例如。 Mobay公司
的輸出應該在以下:
20170308
Rain
Mobay
20170307
Clear
Kingston
20170309
Clear
Kingston
......
JSON:
{
"cod":"200",
"message":0.2902,
"cnt":35,
"list": [
{
"dt":1488985200,
"main":{
"temp":300.1,
"temp_min":299.712,
"temp_max":300.1,
"pressure":1026.69,
"sea_level":1033.03,
"grnd_level":1026.69,
"humidity":100,
"temp_kf":0.39
},
"weather": [
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01d"
}
],
"clouds":{
"all":0
},
"wind":{
"speed":9.02,
"deg":68.0006
},
"sys":{
"pod":"d"
},
"dt_txt":"2017-03-08 15:00:00"
},
{
"dt":1488996000,
"main":{
"temp":300.55,
"temp_min":300.252,
"temp_max":300.55,
"pressure":1025.2,
"sea_level":1031.44,
"grnd_level":1025.2,
"humidity":98,
"temp_kf":0.29
},
"weather": [
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01d"
}
],
"clouds":{
"all":0
},
"wind":{
"speed":9.07,
"deg":67.5009
},
"sys":{
"pod":"d"
},
"dt_txt":"2017-03-08 18:00:00"
}],
"city":{
"id":3489460,
"name":"Montego Bay",
"coord":{
"lat":18.4712,
"lon":-77.9189
},
"country":"JM"
}
}
PHP代碼:
$kingstonJson = file_get_contents('http://api.openweathermap.org/data/2.5/forecast?q=Montego%20Bay,Jam&mode=json&appid=894ae60546cfa979ee945b2a7809f23d');
$mobayJson = file_get_contents('http://api.openweathermap.org/data/2.5/forecast?q=Kingston,Jam&mode=json&appid=894ae60546cfa979ee945b2a7809f23d');
$kingstonWeather = json_decode($kingstonJson);
$mobayWeather = json_decode($mobayJson);
foreach($kingstonWeather->list as $list){
//echo $list->weather->main;
foreach ($list as $b){
//echo $b;// getting an error here
}
foreach ($list->weather as $b){
echo $b->main;
}
我怎樣才能做到這一點?
'$ list-> dt'是一個數字,不是數組,你爲什麼使用'foreach'? – Barmar
這是一個錯誤應該是'$ list'。 –
使用'print_r($ kingstonWeather);'查看包含Kingston天氣數據的PHP對象的友好輸出,這樣您就能夠看到目標屬性的放置位置。 –