PHP打印嵌套JSON值时报Trying to access array offset错误如何解决
报错原因
- 核心原因:你提供的JSON字符串中嵌入了不可见的零宽空格字符,导致
json_decode解析失败,返回null。后续直接对null值执行$obj['items']数组下标访问操作,直接触发该Notice报错。 - 潜在原因:代码没有做容错校验,即使JSON解析正常,若存在部分item缺失
combinations字段、或字段值为null的情况,也会触发同类报错。
修复方案
首先清理JSON字符串中的不可见字符,再增加解析校验和字段存在性判断,修复后代码如下:
// 先过滤JSON字符串中的零宽空格等不可见异常字符 $json_string = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $json_string); // 解析JSON $obj = json_decode($json_string, true); // 判断JSON是否解析成功 if (json_last_error() !== JSON_ERROR_NONE || !is_array($obj) || !isset($obj['items'])) { die('JSON解析失败:' . json_last_error_msg()); } $order_contents = $obj['items']; foreach($order_contents as $order) { // 先判断必填字段是否存在 if (!isset($order['menuItemName'], $order['price'], $order['combinations']) || !is_array($order['combinations'])) { continue; } $menuItemName = $order['menuItemName']; $price = $order['price']; $combinations = $order['combinations']; foreach($combinations as $combination) { // 判断combination的字段是否存在 if (!isset($combination['combinationName'])) { continue; } echo $menuItemName.'-'.$combination['combinationName'].'-'.$price.'.'; } }
说明
- 先通过正则替换清理JSON字符串中的零宽空格、零宽连接符、BOM头等会导致解析失败的不可见字符,保证
json_decode可以正常解析出数组。 - 增加多层容错判断,只要某一层数据不符合预期就跳过处理,避免触发Notice报错的同时保证代码健壮性。
内容的提问来源于stack exchange,提问作者Buy2slay
相关产品推荐
相关产品推荐

