PHP生成JSON时触发Cannot access offset错误的解决咨询
JSON数据读写与删除的正确实现
问题根源
你的代码核心问题是初始写入的是单个JSON对象而非数组,导致后续追加数据时,array_push会把新对象作为属性添加到原对象中,最终生成的JSON结构混乱(混合了对象属性和数组索引),读取时自然无法正确解析为数组进行遍历。
你生成的错误JSON结构:
{ "name": "example name 1", "phone": "111111111", "email": "email@addr.com", "msg": "test message", "0": { "name": "example name 2", "phone": "111111111", "email": "email@addr.com", "msg": "test message 2" } }
这是一个对象而非数组,json_decode后得到的是关联数组,遍历的时候$comment会是字符串(比如第一个元素是"example name 1"),再用$comment[$i]就会触发类型错误。
修正后的写入代码
要始终保持JSON文件内容为数组格式,不管是空还是已有数据。修改后的逻辑:
if ($_POST) { $name = strip_tags($_POST['name']); $phone = strip_tags($_POST['phone']); $msg = strip_tags($_POST['message']); $email = strip_tags($_POST['email']); $file = '../json/contact.json'; $newItem = [ 'name' => $name, 'phone' => $phone, 'email' => $email, 'msg' => $msg ]; // 确保文件存在,不存在则创建空数组的JSON if (!file_exists($file)) { file_put_contents($file, json_encode([], JSON_PRETTY_PRINT)); } $contactContent = file_get_contents($file); $items = json_decode($contactContent, true) ?: []; // 解析失败则用空数组兜底 // 追加新数据到数组 $items[] = $newItem; $jsonData = json_encode($items, JSON_PRETTY_PRINT); file_put_contents($file, $jsonData); }
生成的正确JSON结构始终是数组:
[ { "name": "example name 1", "phone": "111111111", "email": "email@addr.com", "msg": "test message" }, { "name": "example name 2", "phone": "111111111", "email": "email@addr.com", "msg": "test message 2" } ]
修正后的读取代码
现在JSON是数组,遍历逻辑直接访问每个元素的属性即可:
$file = '../json/contact.json'; if (!file_exists($file)) { echo "暂无数据"; exit; } $commentsContent = file_get_contents($file); $comments = json_decode($commentsContent, true) ?: []; foreach ($comments as $comment) { echo $comment['name'] . '<br>'; echo $comment['email'] . '<br>'; echo $comment['phone'] . '<br>'; echo $comment['msg'] . '<br><hr>'; }
删除数据的实现
1. 删除指定索引的元素
比如删除第0个元素:
$file = '../json/contact.json'; if (!file_exists($file)) exit; $items = json_decode(file_get_contents($file), true) ?: []; $indexToDelete = 0; // 要删除的索引 if (isset($items[$indexToDelete])) { array_splice($items, $indexToDelete, 1); file_put_contents($file, json_encode($items, JSON_PRETTY_PRINT)); }
2. 清空所有数据
直接写入空数组的JSON:
$file = '../json/contact.json'; file_put_contents($file, json_encode([], JSON_PRETTY_PRINT));
3. 删除指定条件的元素
比如删除name为"example name 1"的元素:
$file = '../json/contact.json'; if (!file_exists($file)) exit; $items = json_decode(file_get_contents($file), true) ?: []; $items = array_filter($items, function($item) { return $item['name'] !== 'example name 1'; }); // 重新索引数组(可选,保持索引连续) $items = array_values($items); file_put_contents($file, json_encode($items, JSON_PRETTY_PRINT));
内容的提问来源于stack exchange,提问作者Bruce
相关产品推荐
相关产品推荐

