簡體   English   中英

如何解析這個 JSON (PHP & JSON_DECODE)

[英]How to Parse this JSON (PHP & JSON_DECODE)

我正在使用以下 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
}

在 JSON 中獲取maindescription的正確方法是什么?

我已經嘗試了下面的代碼,但它不起作用:

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

使用json_decode()json數據轉換為 php 類型時,它總是將其轉換為對象。 需要明確的是,您可以像這樣訪問天氣的主要和描述屬性:

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

更新:

此外,您還可以通過將 bool(true) $assoc 參數傳遞給json_decode()函數來將數據轉換為關聯數組。

$data = json_decode( $dirty_data, true );

並像這樣提取您的數據:

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

你總是可以做var_dump($data)來看看你有什么以及如何訪問它。
json_decode返回一個 stdClass 而不是數組。
$data->weather[0]->main;
應該是正確的事情。
{} 代表一個對象,[] 代表一個數組。 注意weather:[{...}]這意味着weather 是一個對象數組。

試試

$data = json_decode( $dirty data, true)

如果您提供 true 參數,它不會轉換為對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM