1

我想为我的网站实现一个天气模块。为此,我选择了“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文件

在此处输入图像描述

4

2 回答 2

3

您正在放置一个额外的[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
于 2015-07-11T22:50:09.217 回答
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>';
于 2015-07-11T22:56:41.930 回答