在网站中,使用json_encode打包一个二维数组为json,然后存入cookie中。
数据如下:
array( 0 => array( "key1" => "value1", "key2" => "value2" ), 1 => array( "key1" => "value1", "key2" => "value2" ), 2 => array( "key1" => "value1", "key2" => "value2" ))
打包之后的数据为:
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]
之后对这些数据进行操作,用json_decode解析出来,从中删除一个元素。
删除之后的数据为:
array( 0 => stdClass( "key1" => "value1", "key2" => "value2" ), 2 => stdClass( "key1" => "value1", "key2" => "value2" ))
再次用json_encode打包数据,存入cookie,得到的数据如下:
{"0":{"key1":"value1","key2":"value2"},"2":{"key1":"value1","key2":"value2"}}
如果数据在打包之前,使用sort函数排序一下,得到的数据如下:
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]
可以看出,这是跟键值有联系的。如果数组的键没有从0开始并且是有序索引,键值就会被打包进去,作为json的key,而不是数组的索引。