使用foreach使用PHP解析JSON

时间:2017-01-31 17:19:38

标签: php json foreach

我设法解码并回显JSON提要。运行此命令后

print_r(json_decode($data,true));

这就是我在屏幕上看到的内容:

Array
(
  [sportId] => 29
  [last] => 96466864
  [league] => Array
    (
        [0] => Array
            (
                [id] => 1980
                [events] => Array
                    (
                        [0] => Array
                            (
                                [id] => 667177156
                                [starts] => 2016-11-26T15:00:00Z
                                [home] => Hull City
                                [away] => W.B.A
                                [rotNum] => 2504
                                [liveStatus] => 1
                                [status] => O
                                [parlayRestriction] => 2
                            )
                        [1] => Array
                            (
                                [id] => 672139467
                                [starts] => 2016-12-10T15:00:00Z
                                [home] => Hull City
                                [away] => Crystal Palace
                                [rotNum] => 2510
                                [liveStatus] => 1
                                [status] => O
                                [parlayRestriction] => 2
                            )
                        [2] => Array
                            (
                                [id] => 676973849
                                [starts] => 2016-12-26T15:00:00Z
                                [home] => Burnley
                                [away] => Middlesbrough
                                [rotNum] => 2519
                                [liveStatus] => 1
                                [status] => O
                                [parlayRestriction] => 2
                            )
                        )
                )
        )
)

我需要能够使用 foreach 来遍历此关联数组中的每个[事件],并且能够获得如下结果:

Hull City v W.B.A.
Hull City v Crystal Palace
Burnley v Middlesbrough

我认为一切都已经正确解析了,现在只需要使用正确的语法来回应关联数组的结果,我自己也做不到。

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

$data=json_decode($data,true);//converts in array

    foreach($data['league'] as $key=>$val){// this can be ommited if only 0 index is there after 
//league and $data['league'][0]['events'] can be used in below foreach instead of $val['events'].
      foreach($val['events'] as $keys=>$value){
        echo $value['home'].' v '.$value['away'].'<br>;
    }  
    }

答案 1 :(得分:0)

试试这样..

$data=json_decode($data,true);//convert your json into array
$events = $data['leage'][0]['events'];//events array

foreach($events as $key=>$value)//loop inside your events array
{
  echo $value['home'].' v '.$value['away'].'<br>;
}