无法访问具有json_decode的数组元素


Unable to access array element with json_decode

我使用json_decode从JSON响应中获取数组:

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

这给了我以下内容(我没有包括所有的建立详细信息数组结果)

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来获得业务名称:

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

但我没有得到任何结果。

问题是您正在将$result作为对象访问:

$result->FHRSEstablishment

但是当你调用json_decode时,第二个参数设置为 true ,它会返回一个关联数组,你应该访问它:

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

如果您希望能够使用对象表示法访问$result,则应将其定义为:

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