1

我正在处理来自 wunderground.com 的 json 源代码。作为文档中显示的示例代码。我可以调整和锻炼一些简单的格式。但我坚持这个。我试图用谷歌搜索每个地方,但没有解决方案。

这是示例代码:

<?php
  $json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
  $parsed_json = json_decode($json_string);
  $location = $parsed_json->{'location'}->{'city'};
  $temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
  echo "Current temperature in ${location} is: ${temp_f}\n";
?>

好吧,我需要一些信息,例如pws/station中的“ Cedar Rapids ” :

"pws": {
        "station": [
        {
        "neighborhood":"Ellis Park Time Check",
        "city":"Cedar Rapids",
        "state":"IA",
        "country":"US",
        "id":"KIACEDAR22",
        "lat":41.981174,
        "lon":-91.682632,
        "distance_km":2,
        "distance_mi":1
        }
]
}

(您可以通过单击此获取所有代码:http: //api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json)现在问题是:

  1. 这个数据叫什么?(数组,数组中的数组?)
  2. 我怎么能把这些数据拉出来呢?

问候,

4

1 回答 1

1

station是对象内的一个数组pws

要获取数据,您可以执行以下操作:

<?php
  $json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
  $parsed_json = json_decode($json_string);
  $location = $parsed_json->{'location'}->{'city'};
  $temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
  echo "Current temperature in ${location} is: ${temp_f}\n";

  $stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
  $count = count($stations);
  for($i = 0; $i < $count; $i++)
  {
     $station = $stations[$i];
     if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
     {
        echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
        echo "City: " . $station->{'city'} . "\n";
        echo "State: " . $station->{'state'} . "\n";
        echo "Latitude: " . $station->{'lat'} . "\n";
        echo "Longitude: " . $station->{'lon'} . "\n";
        break;
     }
  }
?>

输出:

Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632
于 2013-11-18T16:52:14.090 回答