为什么unset()会改变json_encode格式化字符串的方式?

时间:2015-06-05 15:57:13

标签: php json unset

今天我注意到了使用unset()和json_decode / json_encode的一些有趣内容。这是代码:

echo "<h3>1) array as string</h3>";
$sa = '["item1","item2","item3"]';
var_dump($sa);
echo "<h3>2) array as string decoded</h3>";
$sad = json_decode($sa);
var_dump($sad);
echo "<h3>3) array as string decoded, then encoded again. <small>(Note it's the same as the original string)</small></h3>";
$sade = json_encode($sad);
var_dump($sade);
echo "<h3>4) Unset decoded</h3>";
unset($sad[0]);
var_dump($sad);
echo "<h3>5) Encode unset array. <small>(Expecting it to look like original string minus the unset value)</small></h3>";
$ns = json_encode($sad);
var_dump($ns);
echo "<h3>6) Decode Encoded unset array</h3>";
var_dump(json_decode($ns));

,结果为:enter image description here

所以我的问题是:为什么unset()会改变json_encode使它成为字符串的方式?我怎样才能获得与原始格式相同的字符串格式?

2 个答案:

答案 0 :(得分:4)

json不需要包含来自偏移零的连续键序列的键。

从标准枚举数组中取消设置值会在该数组的键序列中留下间隙,它不会以任何方式调整其余键;所以json需要通过包含键来反映这种差异

如果要将键重置为偏移0的连续序列,则

unset($sad[0]);
$sad = array_values($sad);

然后json再次编码/解码

Demo

答案 1 :(得分:4)

在数字5中,如果您发现密钥从1开始。通常,数组(在php和js / json中)从零开始。 json中的非零索引数组(或具有非连续数字的数组)是对象文字,而不是数组。如果你想要相同的字符串格式,我建议你json_decode传递第二个参数来强制它到一个数组。然后,您可以使用将数组重新索引为数字的数组函数,例如array_shiftarray_pop。或者当json_encoding数组时,使用array_values自己重新索引数组。