2017-01-31 94 views
-2

我設法解碼並回顯JSON提要。運行這個命令之後使用foreach解析JSON並使用PHP

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 

我認爲所有東西都已經正確解析,現在只是使用正確的語法來回顯聯想數組的結果,這是我自己做不到的。

+0

肯定。 json解析全部完成 - 這就是'json_decode'**做的**。現在,你只是有一個簡單的舊,無聊,簡單的陣列。包含嵌套數組。直到名爲'$ decode ['league'] [0] ['events']'的數組,你必須迭代。然後,這些項目中的每一個都是一個*數組本身*,您可以使用*每隔一個數組*。如:'$ line ['home']' –

回答

1

你可以試試這個:

$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>; 
    } 
    } 
+0

感謝哥們。正是我想要的。 –

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>; 
}