2012-05-28 44 views
-1

訪問數組元素我已經使用json_decode獲取從JSON響應的數組:無法與json_decode

$result = (json_decode($trends,true)); 

這使我以下(I沒有包括所有EstablishmentDetail陣列結果)

Array ([FHRSEstablishment] => Array ([Header] => Array ([#text] => [ExtractDate] => 2012-05-28 [ItemCount] => 5 [ReturnCode] => Success) [EstablishmentCollection] => Array ([EstablishmentDetail] => Array ([0] => Array ([FHRSID] => 248659 [LocalAuthorityBusinessID] => INS/06/06179 [BusinessName] => Ancient Raj [BusinessType] => Restaurant/Cafe/Canteen [BusinessTypeID] => 1 [AddressLine1] => 26 North Lane, Canterbury, [PostCode] => CT2 7EE [RatingValue] => 3 [RatingKey] => fhrs_3_en-GB [RatingDate] => 2010-11-18 [LocalAuthorityCode] => 180 [LocalAuthorityName] => Canterbury City [Scores] => [SchemeType] => FHRS [Geocode] =>) 

,我以爲我」能夠使用foreach才能到BUSINESSNAME:

foreach ($result->FHRSEstablishment->EstablishmentCollection->EstablishmentDetail as $detail){ 
    echo $detail['BusinessName']; 
} 

但我沒有得到任何結果。

+5

'$ result'是一個數組,不是對象,因此使用' - >'不起作用。 –

+0

如果您想要更多答案,請格式化數組輸出。 –

+0

請在使用它們的同時瞭解語言特性:http://php.net/array – hakre

回答

4

的問題是,你所訪問的$result作爲一個對象:

$result->FHRSEstablishment 

但是當你調用json_decode設置爲true第二個參數,它返回一個關聯數組,你應該訪問如:

$result['FHRSEstablishment']['EstablishmentCollection'] //... 

如果你希望能夠與對象符號來訪問你的$result,你應該把它定義爲:

$result = json_decode($trends) //without 2nd parameter = true 
+0

非常感謝,我確實希望它成爲一個數組。仍然無法訪問關聯數組,我會再看看數組輸出。 – Textus