duan032225 2014-10-18 18:20
浏览 86
已采纳

如何从JSON weather api中提取特定数据

I found some (most) of the following code on wunderground and it works. I can't figure out how to directly pull out specific information. Here's the code that will run as is:

<?php 


function iterate($name, $object)
{
   foreach ($object as $key => $value)
   {
      if (is_object($value))
      {
         iterate("${name}->${key}", $value);
      }
      else if (is_array($value))
      {
         $n = count($value);
         for ($i = 0; $i < $n; ++$i)
         {
            if (is_object($value[$i]))
            {
               iterate("${name}->${key}[$i]", $value[$i]);
            }
            else
            {
              print "${name}->${key}[$i] = '$value'
";
              echo "<br>";
            }
         }
      }
      else
      {
          print "${name}->${key} = '$value'
";
          echo "<br>";
          print "${name}->${key} = '$value'
";
          print "$name->$key
";
          print_r ($value);
          echo "<br> <br>";
      }
    }

}

$api = 'http://api.wunderground.com/api';
$key = 'a66c7dca62f80c59'; // 
$features = 'geolookup/forecast10day'; // your desired features here
$query = 'q/MA/KBOS'; // your query here
$data = json_decode(file_get_contents("$api/$key/$features/q/$query.json"));


iterate('data', $data);

Now's here the code that I added but is not working:

   $test = $data->{'forecast'}->{'txt_forecast'}->{'forecastday[4]'}->{'fcttext'};
   print "$test";

?>

I've decoded the json query into $data but how do I get at a specific piece of information?

  • 写回答

2条回答 默认 最新

  • doucong1268 2014-10-18 20:17
    关注
    $api = 'http://api.wunderground.com/api';
    $key = 'a66c7dca62f80c59'; //
    $features = 'geolookup/forecast10day'; // your desired features here
    $query = 'q/MA/KBOS'; // your query here
    $data = json_decode(file_get_contents("$api/$key/$features/q/$query.json"),1);
    
    echo $data['forecast']['txt_forecast']['forecastday'][4]['fcttext'];
    

    of course in the real world you'd' would want to check that all this stuff exists before referencing any of it

    $forecastdays = $data['forecast']['txt_forecast']['forecastday'];
    
    foreach ($forecastdays as $forecastday){
        echo $forecastday['fcttext'] . '<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图