duan032225
duan032225
2014-10-18 18:20

如何从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 doucong1268 7年前
    $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>';
    }
    
    点赞 评论 复制链接分享
  • dsogx84602 dsogx84602 7年前

    Have you tried

    $data[0]->{'forecast'}
    

    Also if you prefer associative arrays, just add true as a second argument to your json_decode, and you can access your data like so:

    $data[0]['forecast']
    

    PS. showing us a portion of the JSON will make it easier for us to help you solve your problem.

    点赞 评论 复制链接分享