3

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

$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" } }

这是正常的,将它保留为一个数组,但是一旦我取消设置数组的一部分,它就会将它变成一个 obj。

$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" } }

如何保持一致性?

4

3 回答 3

1

正如 Marc B 在评论中解释的那样,您需要将数组重新索引为从零开始的索引。在 PHP 中可以通过以下方式完成array_values

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

另见:

于 2013-08-20T19:59:58.723 回答
1

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

于 2013-08-20T20:00:42.297 回答
0

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

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

于 2013-08-20T20:03:41.927 回答