PHP中json_encode将数组转为对象的问题及解决诉求
解决PHP中unset数组元素后json_encode将数组转为对象的问题
问题根源在于:PHP中如果数组的索引不是连续的数字序列(比如unset掉索引0后,剩下的索引是1、2),json_encode会默认把这个数组序列化为JSON对象而非数组,导致后续模块解析时结构不符合预期。
可行解决方案
直接对处理后的数组重新索引,让它恢复连续的数字索引,就能让json_encode继续将其识别为JSON数组,同时不改变原对象的其他结构。
方法一:unset后用array_values()重置索引
修改你的编辑代码,在unset元素后添加数组重新索引的步骤:
$a = json_decode( $json ); foreach( $a->items as $key => $item ){ if( $item == 'A' ){ unset( $a->items[$key] ); break; } } // 关键步骤:重置数组索引为连续的0、1、2... $a->items = array_values($a->items); $json = json_encode( $a ); $decoded = json_decode( $json );
执行后生成的JSON会保持items为数组:
{"name":"example","items":["B","C"]}
解码后的结构也符合预期:
stdClass Object ( [name] => example [items] => Array ( [0] => B [1] => C ) )
方法二:先转为数组处理(可选)
如果习惯用数组操作,也可以先把对象的items属性转成数组处理,完成后重新索引再赋值回去,效果和方法一一致:
$a = json_decode( $json ); // 将对象属性转为数组 $items = (array)$a->items; foreach( $items as $key => $item ){ if( $item == 'A' ){ unset( $items[$key] ); break; } } // 重置索引后赋值回对象 $a->items = array_values($items); $json = json_encode( $a );
为什么之前的标志位无效
像JSON_FORCE_OBJECT是强制所有数组转为对象,和需求相反;JSON_NUMERIC_CHECK只是处理字符串转数字,都无法解决非连续索引数组被转成对象的问题,核心解决思路还是让数组恢复连续的数字索引。
内容的提问来源于stack exchange,提问作者Carlson Soares
相关产品推荐
相关产品推荐

