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

PHP使用foreach遍历第三层数组时出现Fatal error如何解决?

问题原因

你的遍历逻辑存在层级错误:$countname1['cities']本身是包含prefix、options两个键的关联数组,不需要对该层级做foreach遍历。
你现在对cities执行foreach循环时,第一轮循环的$cntrykey2为prefix,对应的$cntrys是值为_city-的字符串,尝试对字符串取options数组索引,自然触发「不能对字符串使用字符串偏移量」的报错。

解决方法

直接去掉第二层多余的foreach,从cities中直接取options字段遍历即可,修正后的代码如下:

foreach($countryarr1['countries'] as $countkey1 => $countname1){ 
    // 直接取cities下的options遍历,不需要遍历cities本身
    foreach($countname1['cities']['options'] as $optionskey1 => $optionsarr1){
        var_dump($optionsarr1);
    }
}

如果确实有需要同时读取cities下的prefix字段,直接单独取值即可,不需要遍历:

foreach($countryarr1['countries'] as $countkey1 => $countname1){ 
    // 可单独获取cities的prefix值
    $city_prefix = $countname1['cities']['prefix'];
    foreach($countname1['cities']['options'] as $optionskey1 => $optionsarr1){
        var_dump($optionsarr1);
    }
}

内容的提问来源于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 15:18:06