2017-08-03 50 views
-1

我正在尝试使用以下API:https://openweathermap.org来获取当前天气。如何解析此JSON(PHP&JSON_DECODE)

{ 
    "coord":{ 
    "lon": 
    "lat": 
}, 
"weather":[ 
    { 
    "id":521, 
    "main":"Rain", 
    "description":"shower rain", 
    "icon":"09n" 
    } 
], 
"base":"stations", 
"main":{ 
    "temp":289.22, 
    "pressure":1004, 
    "humidity":82, 
    "temp_min":288.15, 
    "temp_max":290.15 
}, 
"visibility":10000, 
"wind":{ 
    "speed":4.1, 
    "deg":210 
}, 
"clouds":{ 
    "all":100 
}, 
"dt":1501793400, 
"sys":{ 
    "type":1, 
    "id":5060, 
    "message":0.0039, 
    "country":"GB", 
    "sunrise":1501734589, 
    "sunset":1501790444 
}, 
"id":3333126, 
"name":"Borough of Blackburn with Darwen", 
"cod":200 
} 

如果我想要天气 - >主要和天气 - >描述我该怎么做?

目前我做的:

$url = "http://api.openweathermap.org/data/2.5/weather?lat=" . $latitude . "&lon=" . $longitude . "&APPID=71f4ecbff00aaf4d61d438269b847f11"; 
$dirty_data = file_get_contents($url); 

$data = json_decode($dirty_data); 
echo $data['weather']['main']; 

而且什么也没有发生,我还能设法得到它的工作?

+0

使用'var_dump($ data)'来查看您的数组 – MAZux

+0

尝试$ data.weather.main – Lekens

+0

您发布的json无效。 –

回答

0

当使用json_decode()json数据转换为php类型时,它将始终将其转换为对象。需要明确的是,您可以访问天气的主要和描述特性是这样的:

echo $data->weather[0]->main // outputs main 
echo $data->weather[0]->description // outputs description 

更新:

此外,还可以通过传递布尔(真)$ assoc命令参数的json_decode()数据转换为关联数组功能。

$data = json_decode($dirty_data, true); 

,并提取您的数据是这样的:

echo $data['weather'][0]['main']; // for main 
echo $data['weather'][0]['description']; // for description 
0

哟总是可以做var_dump($data)看看你有什么,以及如何访问它。
json_decode返回一个stdClass而不是一个数组。
$data->weather[0]->main;
应该是正确的。
{}象征一个对象,[]象征一个数组。通知weather:[{...}]这意味着天气是一组对象。

0

尝试

$数据= json_decode($脏数据,真)

,如果你提供真正的争论它不会转换为对象。