You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP遍历嵌套JSON数据时报Cannot access offset of type string错误如何解决

报错原因
  • 你的$countname1['cities']是包含prefix、options两个键的关联数组,无需遍历cities的所有子项,直接访问$countname1['cities']['options']即可拿到城市选项数组
  • 你新增的第二层foreach($countname1['cities'] as $cntrykey2 => $cntrys)会依次遍历cities下的两组键值:
    • 遍历到prefix键时,$cntrys是字符串值_city-,此时尝试访问$cntrys['options']就会触发「无法在字符串上访问字符串类型偏移」的报错
修复方案

直接移除多余的第二层cities遍历,调整后代码如下:

foreach($countryarr1['countries'] as $countkey1 => $countname1){ 
    // 直接读取cities下的options数组遍历
    foreach($countname1['cities']['options'] as $optionskey1 => $optionsarr1){
        var_dump($optionsarr1);
        // 如需输出城市编码可使用 echo $optionsarr1['code'];
    }
}

如果需要用到cities下的prefix值,直接访问$countname1['cities']['prefix']即可,无需遍历。

调试建议

后续遇到同类数组遍历报错时,可先用var_dump()打印当前层级的变量类型和结构,确认是否符合你的遍历预期,即可快速定位问题。

内容的提问来源于stack exchange,提问作者Heinrich Picar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:54:03