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

PHP删除JSON子数组元素后转为对象异常问题求助

问题原因
  • 你使用unset()删除数组元素时,PHP不会自动重置数组的数字索引,会保留原有索引,导致data对应的数组变成非连续索引数组
  • PHP的json_encode()方法处理非连续数字索引数组时,会默认将其转换为JSON对象格式,因此才会出现你遇到的带数字键的结构
正确实现方式

删除元素后使用array_values()重置数组索引为从0开始的连续序列即可,修改后的代码如下:

$pos = $_POST['position'];
$jsn = file_get_contents('../datamer/archives/'.$sbd.".json");
$arr = json_decode($jsn, true);
$acc = $arr["data"];   

// 可选优化:先判断索引是否存在,避免报错
if (isset($acc[$pos])) {
    unset($acc[$pos]);  
}

// 重置数组索引为连续序列
$arr["data"] = array_values($acc);
file_put_contents('../datamer/archives/'.$sbd.".json",json_encode($arr,JSON_PRETTY_PRINT));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:06:06