【问题标题】:Openweathermap: json (min and max temp)Openweathermap:json(最低和最高温度)
【发布时间】:2015-09-30 11:46:31
【问题描述】:

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

【问题讨论】:

    标签: php json weather-api openweathermap


    【解决方案1】:

    您正在添加一个额外的[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>';
    

    要获取摄氏度,请附上&amp;units=metric

    http://api.openweathermap.org/data/2.5/forecast/daily?q=london&mode=json&units=metric
    

    【讨论】:

    • 我得到的值是°F吗?如何将此值转换为°C?
    • @KlippOhei 检查我修改后的答案,让 API 更容易做到这一点。 (当然你可以用(F - 32) * 5/9自己转换。
    【解决方案2】:

    你有一个额外的 [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>';
    

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 2012-10-16
      • 2016-01-22
      • 2014-09-09
      • 2020-05-05
      • 2020-08-29
      • 2021-02-11
      • 2021-09-04
      • 2019-08-08
      相关资源
      最近更新 更多