我有一个数组,我通过json_encode,它包围第一个数组周围的数组括号,但包围第二个数组周围的对象附件{}并编号嵌套数组。它没有造成任何错误,只是想知道为什么会发生这种情况。
{
"data": {
"first_array": [
{
"meta": {
"slug": "rank",
"weight": "100",
"description": "lorem ipsum",
"importance": {
"value": 2,
"max": 5
}
},
"scores": {
"results": {
"slug": "rank",
"type": "int",
"value": "4"
}
}
},
{
"meta": {
"slug": "rank",
"weight": "100",
"description": "lorem ipsum",
"importance": {
"value": 2,
"max": 5
}
},
"scores": {
"results": {
"slug": "rank",
"type": "int",
"value": "4"
}
}
}
],
"second_array": {
"2": {
"meta": {
"slug": "this",
"weight": "75",
"description": "lorem ipsum",
"importance": {
"value": 1,
"max": 5
}
},
"scores": {
"results": {
"slug": "this",
"type": "boolean",
"value": 1,
"code": 200
}
}
},
"3": {
"meta": {
"slug": "that",
"weight": "200",
"description": "lorem ipsum",
"importance": {
"value": 3,
"max": 5
}
},
"scores": {
"results": {
"slug": "that",
"type": "boolean",
"value": 1
}
}
}
}
}
}
这是数组的print_r
Array
(
[data] => Array
(
[first_array] => Array
(
[0] => Array
(
[meta] => Array
(
[slug] => rank
[weight] => 100
[description] => lorem ipsum
[importance] => Array
(
[value] => 2
[max] => 5
)
)
[scores] => Array
(
[results] => Array
(
[slug] => rank
[type] => int
[value] => 4
)
)
)
[1] => Array
(
[meta] => Array
(
[slug] => rank
[weight] => 100
[description] => lorem ipsum
[importance] => Array
(
[value] => 2
[max] => 5
)
)
[scores] => Array
(
[results] => Array
(
[slug] => rank
[type] => int
[value] => 4
)
)
)
)
[second_array] => Array
(
[2] => Array
(
[meta] => Array
(
[slug] => this
[weight] => 100
[description] => lorem ipsum
[importance] => Array
(
[value] => 2
[max] => 5
)
)
[scores] => Array
(
[results] => Array
(
[slug] => this
[type] => boolean
[value] => 1
[code] => 200
)
)
)
[3] => Array
(
[meta] => Array
(
[slug] => that
[weight] => 100
[description] => lorem ipsum
[importance] => Array
(
[value] => 2
[max] => 5
)
)
[scores] => Array
(
[results] => Array
(
[slug] => that
[type] => boolean
[value] => 1
)
)
)
)
)
)
答案 0 :(得分:3)
因为第二个是associative array(以字符串作为键)。 JS数组只能有数字索引。
自PHP 5.3起,您可以强制json_encode
仅使用JSON_FORCE_OBJECT输出对象
答案 1 :(得分:0)
可能会发生这种情况,因为你的first_array实际上是一个从index = 0开始并且是连续的数组,而second_array是从index = 2开始的,所以函数使用索引(作为字符串)< =>价值联想。
乙
答案 2 :(得分:0)
第一个从键0开始,所以它看起来像一个标准的数字数组。即javascript中的first[0]
将为您提供第一个元素。
但第二个从2开始,不能放入标准的javascript数组。即PHP中的$ second [2]在javascript中实际上是second[0]
(如果它确实将它转换为数组)。
这两个数字系统不兼容。保存为对象,允许对数据进行任意字符串键。 (更像是一个关联数组 - 即使数字作为键,而不是数字数组。一个javascript数字数组不能跳过键)
你可以打电话
$array['data']['second_array'] = array_values($array['data']['second_array']);
丢弃第二个数组的当前键,并获取新的键 - 它将从0开始,并在转换时形成一个普通的javascript数组。
答案 3 :(得分:0)
只是重现您的状态(并尝试解释)的示例
$a = Array("a","b","c","d");
echo json_encode($a); // ["a","b","c","d"]
unset($a[2]);
echo json_encode($a); // {"0":"a","1":"b","3":"d"}
在第一种情况下,我们有一个纯数组(数字)。所以这个json字符串是一个数组rappresentation ["a","b","c","d"]
。
但是当我们取消设置第三个元素时,数值数组将是关联数组(因为订单尚未得到遵守)。关联数组(带有数字索引但不是顺序索引)在json中就像简单对象一样。