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
相关产品推荐
相关产品推荐

