在PHP中获取数组数据

时间:2014-03-12 08:26:36

标签: php arrays json api

我使用以下代码获取了JSON数据。

$json = file_get_contents('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139'); 
$data = json_decode($json,true);

print_r($data);
foreach($data as $key => $datas){
$datas[$key];
   } 

这是解码的json

   Array(
[coord] => Array
    (
        [lon] => 139
        [lat] => 35
    )

[sys] => Array
    (
        [message] => 0.0053
        [country] => JP
        [sunrise] => 1394571511
        [sunset] => 1394614136
    )

[weather] => Array
    (
        [0] => Array
            (
                [id] => 802
                [main] => Clouds
                [description] => scattered clouds
                [icon] => 03d
            )

    )

[base] => cmc stations
[main] => Array
    (
        [temp] => 289.82
        [pressure] => 1013
        [temp_min] => 289.82
        [temp_max] => 289.82
        [humidity] => 30
    )

[wind] => Array
    (
        [speed] => 3.08
        [gust] => 8.74
        [deg] => 230
    )

[clouds] => Array
    (
        [all] => 48
    )

[dt] => 1394611401
[id] => 1851632
[name] => Shuzenji
[cod] => 200
)

然后我尝试使用Foreach方法显示数据,但我无法正确使用。

有人可以帮我这个.......

3 个答案:

答案 0 :(得分:2)

您可以轻松使用以下示例来读取PHP数组:

echo $data['coord']['lon'];
echo $data['coord']['lat'];
echo $data['sys']['message'];
echo $data['sys']['country'];
echo $data['sys']['sunrise'];
echo $data['sys']['sunset'];
.... And so on

目前您收到:

Array
(
    [coord] => Array
        (
            [lon] => 139
            [lat] => 35
        )
[sys] => Array
    (
        [message] => 0.0422
        [country] => JP
        [sunrise] => 1394571511
        [sunset] => 1394614136
    )

[weather] => Array
    (
        [0] => Array
            (
                [id] => 802
                [main] => Clouds
                [description] => scattered clouds
                [icon] => 03d
            )

    )

[base] => cmc stations
[main] => Array
    (
        [temp] => 289.26
        [pressure] => 1013
        [temp_min] => 289.26
        [temp_max] => 289.26
        [humidity] => 30
    )

[wind] => Array
    (
        [speed] => 3.08
        [gust] => 8.74
        [deg] => 252
    )

[clouds] => Array
    (
        [all] => 48
    )

[dt] => 1394612300
[id] => 1851632
[name] => Shuzenji
[cod] => 200

答案 1 :(得分:1)

如果您确实要显示所有键/值,请尝试:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($iterator as $key => $value) {
    echo "$key => $value<br>";
}

答案 2 :(得分:0)

  • $ data由数组中的数组组成。
  • 所以你需要正确地解析它。
  • 使用嵌套的Foreach。