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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。