使用json_decode解析银行API返回JSON提取嵌套数组字段方法咨询
代码问题与修复方案
核心错误点
- 调用
json_decode时第二个参数传了true,返回值为关联数组格式,你后续用对象运算符->访问属性的写法完全不兼容 AllBillerListRes是顶层结构下的直接字段,不是数组,不需要加[0]下标取值
修正后的代码(保持关联数组访问方式)
$decoded = json_decode($json_string, true); // 直接按数组层级取biller数组 $billerList = $decoded['AllBillerListRes']['biller']; foreach($billerList as $item) { $name = $item['nameEn']; $icon = $item['iconUrl']; echo '<br> Name ->' . $name . '<br> IconURL ->' . $icon; }
可选处理方式(对象访问写法)
如果你习惯用对象运算符->访问属性,只要把json_decode的第二个参数去掉即可,示例如下:
// 第二个参数不传默认是false,返回标准对象 $decoded = json_decode($json_string); $billerList = $decoded->AllBillerListRes->biller; foreach($billerList as $item) { $name = $item->nameEn; $icon = $item->iconUrl; echo '<br> Name ->' . $name . '<br> IconURL ->' . $icon; }
内容的提问来源于stack exchange,提问作者Asim
相关产品推荐
相关产品推荐

