我想为我的网站实施天气模块。为此,我选择了“Openweathermap”。
我想获得今天和明天的最低和最高温度。
PHP
$json_string = file_get_contents("http://api.openweathermap.org/data/2.5/forecast/daily?q=london&mode=json");
$jsonData = json_decode($json_string, true);
$min_1 = $jsonData['list'][0]['temp'][0]['min'];
$max_1 = $jsonData['list'][0]['temp'][0]['max'];
$min_2 = $jsonData['list'][1]['temp'][0]['min'];
$max_2 = $jsonData['list'][1]['temp'][0]['max'];
echo $min_1.' - '.$max_1.'<br><br>';
echo $min_2.' - '.$max_2.'<br><br>';
但是使用这段代码我没有输出(除了两个“ - ”)。
json文件
答案 0 :(得分:2)
您需要额外[0]
:
// V removed [0], temp doesn't have another array in an array
$min_1 = $jsonData['list'][0]['temp']['min'];
$max_1 = $jsonData['list'][0]['temp']['max'];
$min_2 = $jsonData['list'][1]['temp']['min'];
$max_2 = $jsonData['list'][1]['temp']['max'];
echo $min_1.' - '.$max_1.'<br><br>';
echo $min_2.' - '.$max_2.'<br><br>';
要获得摄氏度,请附上&units=metric
:
http://api.openweathermap.org/data/2.5/forecast/daily?q=london&mode=json&units=metric
答案 1 :(得分:0)
你有一个额外的[0]会破坏你的代码(第3到第6行)
$json_string = file_get_contents("http://api.openweathermap.org/data/2.5/forecast/daily?q=london&mode=json");
$jsonData = json_decode($json_string, true);
$min_1 = $jsonData['list'][0]['temp']['min'];
$max_1 = $jsonData['list'][0]['temp']['max'];
$min_2 = $jsonData['list'][1]['temp']['min'];
$max_2 = $jsonData['list'][1]['temp']['max'];
echo $min_1.' - '.$max_1.'<br><br>';
echo $min_2.' - '.$max_2.'<br><br>';