ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:13:36 24 4
gpt4 key购买 nike

我今天使用 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 使其成为字符串的方式?以及如何实现与原始字符串格式相同的字符串格式?

最佳答案

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

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

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

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

然后再次json编码/解码

Demo

关于php - 为什么 unset() 会改变 json_encode 格式化字符串的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670865/

24 4 0
文章推荐: ios - 我将如何以编程方式更改单元格的背景颜色
文章推荐: javascript - 在 JavaScript/NodeJS 中压缩十六进制字符串
文章推荐: node.js - 通过 npm 安装 Node iconv 失败
文章推荐: ios - UIImagePickerController 相机无法快速工作
可可西里
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com