[英]How to Parse this JSON (PHP & JSON_DECODE)
I am using the following API: https://openweathermap.org and it gives a JSON response to get the current weather.我正在使用以下 API: https : //openweathermap.org ,它提供 JSON 响应以获取当前天气。
{
"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
}
What is the correct way to go about getting the main
and description
in the JSON?在 JSON 中获取
main
和description
的正确方法是什么?
I have attempted the code below but it doesn't work:我已经尝试了下面的代码,但它不起作用:
$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'];
When using json_decode()
to convert json
data to php type, it will always convert it into an object.使用
json_decode()
将json
数据转换为 php 类型时,它总是将其转换为对象。 To be clear you can access weather's main and description property like this:需要明确的是,您可以像这样访问天气的主要和描述属性:
echo $data->weather[0]->main // outputs main
echo $data->weather[0]->description // outputs description
Besides you can also convert data into an associative array by passing bool(true) $assoc argument to the json_decode()
function.此外,您还可以通过将 bool(true) $assoc 参数传递给
json_decode()
函数来将数据转换为关联数组。
$data = json_decode( $dirty_data, true );
And extract your data like this:并像这样提取您的数据:
echo $data['weather'][0]['main']; // for main
echo $data['weather'][0]['description']; // for description
Yo can always do var_dump($data)
to see what you have and how to access it.你总是可以做
var_dump($data)
来看看你有什么以及如何访问它。
json_decode
returns a stdClass not an array. json_decode
返回一个 stdClass 而不是数组。
$data->weather[0]->main;
Should be the right thing.应该是正确的事情。
{} symbolizes an object and [] symbolizes an array. {} 代表一个对象,[] 代表一个数组。 Notice
weather:[{...}]
which means weather is an array of objects.注意
weather:[{...}]
这意味着weather 是一个对象数组。
Try试试
$data = json_decode( $dirty data, true) $data = json_decode( $dirty data, true)
It doesn't convert to an object if you supply the true argument.如果您提供 true 参数,它不会转换为对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.