PHP对象内嵌数组删除键后重新索引避免JSON序列化转对象问题
问题原因
PHP数组在删除元素后会保留原有索引,形成非连续的整数索引数组。这类数组在执行json_encode时会被识别为关联数组,序列化为JSON对象结构,因此后续json_decode时会被转为stdClass对象,而非原有的数组类型。
解决方案
单层级数组处理(仅处理events数组)
删除目标元素后,直接用array_values()对events数组做重索引即可,示例代码如下:
// 原有删除元素操作 unset($obj->details->events[1]); // 新增重索引操作 $obj->details->events = array_values($obj->details->events); // 后续执行json_encode/json_decode都不会改变events的数组类型
多层嵌套数组通用处理
如果对象内存在多层嵌套的数组都需要处理,可以写递归函数统一做重索引:
function reindex_nested_arrays($data) { // 处理对象属性 if (is_object($data)) { foreach (get_object_vars($data) as $prop => $value) { $data->$prop = reindex_nested_arrays($value); } return $data; } // 处理数组 elseif (is_array($data)) { // 重索引当前数组为连续整数索引 $data = array_values($data); // 递归处理数组内的每个元素 foreach ($data as $key => $value) { $data[$key] = reindex_nested_arrays($value); } return $data; } // 基础类型直接返回 return $data; } // 调用方式:所有元素删除操作完成后执行一次即可 $obj = reindex_nested_arrays($obj);
内容的提问来源于stack exchange,提问作者adhirath wcities
相关产品推荐
相关产品推荐

