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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料