You need to enable JavaScript to run this app. PHP使用foreach遍历嵌套数组出现Illegal string offset错误求助
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用foreach遍历嵌套数组出现Illegal string offset错误求助

问题排查与解决方案

现有代码错误点

  • 混淆了foreach遍历的键名与值:第一层foreach ($response as $list => $val)中,$list是外层数组的键名(字符串类型:status/error/list),$val才是键对应的值。你直接用字符串类型的$list执行第二层foreach遍历,自然触发Illegal string offset报错,字符串无法作为数组被遍历。
  • 缺少数组类型判断:外层数组的status、error对应的值是整数类型,直接对非数组类型执行遍历也会触发报错。
  • 遍历层级与数组实际结构不匹配:数组实际嵌套层级为「外层→list数组→子项数组→data数组」,现有代码的层级对应逻辑完全错位,无法正常输出内容。

解决方案

1. 适配当前数组结构的定制化遍历代码

foreach ($response as $key => $value) {
    // 非数组类型直接输出
    if (!is_array($value)) {
        echo $key . ": " . $value . "\n";
        continue;
    }
    // 遍历list下的所有子项
    if ($key === 'list') {
        foreach ($value as $index => $item) {
            echo "list[" . $index . "]:\n";
            foreach ($item as $attrKey => $attrVal) {
                if (!is_array($attrVal)) {
                    echo "  " . $attrKey . ": " . $attrVal . "\n";
                    continue;
                }
                // 遍历data子数组
                echo "  " . $attrKey . ":\n";
                foreach ($attrVal as $dataIndex => $data) {
                    echo "    [" . $dataIndex . "]: " . $data . "\n";
                }
            }
        }
    }
}

2. 通用任意层级嵌套数组递归遍历代码

如果后续数组嵌套结构有变化,可以用递归方法兼容所有场景:

function traverseArr($arr, $indentLevel = 0) {
    $indent = str_repeat("  ", $indentLevel);
    foreach ($arr as $key => $val) {
        if (is_array($val)) {
            echo $indent . $key . ":\n";
            traverseArr($val, $indentLevel + 1);
        } else {
            echo $indent . $key . ": " . $val . "\n";
        }
    }
}
// 调用方法遍历
traverseArr($response);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 11:39:02