PHP JSON编码在未设置时将密钥转换为字符串


PHP JSON encoding turns key to string when unset

你们能帮我解释一下这里发生了什么吗。

$data[0] = array("one" => "uno", "two" => "dos", "three" => "tres");
$data[1] = array("one" => "uno", "two" => "dos", "three" => "tres");
//unset($data[0]);
$encode = json_encode($data);
$decode = json_decode($encode);
var_dump($decode);

输出:

array(2) { [0]=> object(stdClass)#1 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } [1]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }

这是正常的保持它作为一个数组,但一旦我取消设置数组的一部分,它就会将其变成一个对象

$data[0] = array("one" => "uno", "two" => "dos", "three" => "tres");
$data[1] = array("one" => "uno", "two" => "dos", "three" => "tres");
unset($data[0]);
$encode = json_encode($data);
$decode = json_decode($encode);
var_dump($decode);

输出:

object(stdClass)#1 (1) { ["1"]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }

如何保持一致性?

我会在选项中查看json_encode。我认为JSON_FORCE_OBJECT应该强制恒定。

正如Marc B在一条注释中所解释的,您需要将数组重新索引为从零开始的索引。在可以用array_values:完成的PHP中

$encode = json_encode(array_values($data));

另请参阅:

  • 帮助编辑JSON以生成数组而不是"字典"(2011年6月)

Javascript区分数组和对象。PHP只有数组可以同时覆盖这两种类型。

连续数字0开始的PHP数组被编码为Javascript数组,其他任何数组都被编码为对象。