从json数组中读取项目

时间:2018-04-10 12:15:43

标签: php json

我正在尝试显示从在线API收到的有轨电车时间。我收到的json如下:

    Array
    (
    [@odata.context] => 
 https://opendataclientapi.azurewebsites.net/odata/$metadata#Metrolinks(StationLocation,Id,Dest1,Wait1,Dest2,Wait2,Dest3,Wait3,MessageBoard)
    [value] => Array
        (
            [0] => Array
                (
                    [StationLocation] => Deansgate - Castlefield
                    [Id] => 272
                    [Dest1] => 
                    [Wait1] => 
                    [Dest2] => 
                    [Wait2] => 
                    [Dest3] => 
                    [Wait3] => 
                    [MessageBoard] => Today Manchester City welcome Liverpool to the Etihad Stadium. KO is at 19:45 and services are expected to be busier than usual. Please plan your journey ahead.
                )

            [1] => Array
                (
                    [StationLocation] => Deansgate - Castlefield
                    [Id] => 458
                    [Dest1] => East Didsbury
                    [Wait1] => 0
                    [Dest2] => Altrincham
                    [Wait2] => 2
                    [Dest3] => 
                    [Wait3] => 
                    [MessageBoard] => Today Manchester City welcome Liverpool to the Etihad Stadium. KO is at 19:45 and services are expected to be busier than usual. Please plan your journey ahead.
                )

            [2] => Array
                (
                    [StationLocation] => Deansgate - Castlefield
                    [Id] => 459
                    [Dest1] => Piccadilly
                    [Wait1] => 3
                    [Dest2] => Etihad Campus
                    [Wait2] => 4
                    [Dest3] => 
                    [Wait3] => 
                    [MessageBoard] => Today Manchester City welcome Liverpool to the Etihad Stadium. KO is at 19:45 and services are expected to be busier than usual. Please plan your journey ahead.
                )

        )

)

如何获取每个项目,例如StationLocation,Dest1和Wait1?

目前我正在使用以下循环,但它只会导致返回所有记录

$results = json_decode($response->getBody(),true);
foreach($results->Array as $result) {
       print_r($result);
    }

1 个答案:

答案 0 :(得分:2)

这是你如何做到的,你回应数组元素:

$results = json_decode($response->getBody(),true);
foreach($results->Array as $result) {
   // for example echo $result['element_in_array'];
   echo $result['StationLocation'];
}