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

Why does unset() change the way json_encode formats the string?

我今天使用 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));

结果:

所以我的问题是:为什么 unset() 会改变 json_encode 使其成为字符串的方式?以及如何实现与原始字符串格式相同的字符串格式?

json 不需要包含从偏移量零开始的连续键序列的键。

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

来反映这种差异

如果您想再次将键重置为从偏移量 0 开始的连续序列,则

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

然后 json encode/decode 再次

Demo

在数字 5 中,如果您注意到键从 1 开始。通常数组(在 php 和 js/json 中)从零开始。 json 中的非零索引数组(或具有非连续数字的数组)是对象文字,而不是数组。如果你想要相同的字符串格式,我建议你 json_decode 传递第二个参数以将其强制为数组。然后您可以使用数组函数将数组重新索引为数字,例如 array_shift or array_pop. Or when json_encoding the array, re-index the array yourself with array_values.