我试图显示附近所有气象站的列表。我有代码:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string);
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (count($station) > 1)
{
echo "City: " . $station->{'city'} . "'n";
echo "State: " . $station->{'state'} . "'n";
echo "Latitude: " . $station->{'lat'} . "'n";
echo "Longitude: " . $station->{'lon'} . "'n";
}
}
但目前它没有显示任何东西,我已经搜索了例子,但我找不到这个问题的任何解决方案。
或者,您可以使用一个简单的foreach
来迭代这些值。考虑这个例子:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array
$desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station'];
foreach($desired_values as $key => $value) {
echo "<hr/>";
echo "City: " . $value['city'] . "<br/>";
echo "State: " . $value['state'] . "<br/>";
echo "Latitude: " . $value['lat'] . "<br/>";
echo "Longitude: " . $value['lon'] . "<br/>";
echo "<hr/>";
}
样本小提琴