多维数组给出不同的结果JSON_EN code [英] JSON_ENCODE of multidimensional array giving different results

查看:158
本文介绍了多维数组给出不同的结果JSON_EN code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在做json_en code在PHP多维数组,我注意到一个不同的输出简单地命名阵列中的一个,而不是不给它们命名。例如:

When doing a json_encode a multidimensional array in PHP, I'm noticing a different output simply by naming one of the arrays, as opposed to not naming them. For Example:

$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
json_encode($arrytest)

给多个JSON对象的单个阵列

gives a single array of multiple json objects

[{"a":1,"b":2},{"c":3},{"d":4}];


而只是分配一个名称中间阵列


whereas simply assigning a name to the middle array

$arrytest = array(array('a'=>1, 'b'=>2),"secondarray"=>array('c'=>3),array('d'=>4));
json_encode($arrytest)

{"0":{"a":1,"b":2},"secondarray":{"c":3},"1":{"d":4}};

为什么会第一选项不到位的用1返回相同的reasults作为第二execptsecondarray

why would the 1st option not return the same reasults as the 2nd execpt with "1" in place of "secondarray"

推荐答案

在JSON,阵列 [] 只有每天有数字键,而对象 {} 有字符串属性。在你的第二个例子阵列关键列入迫使整个外部结构是必然的对象。两个例子内的物体被制成,因为包含字符串键的 A,B,C,D

In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.

如果你使用的第一个例子中的 JSON_FORCE_OBJECT 选项,你应该得到一个相似的结构到第二,与外部结构的对象,而不是一个数组。如果没有指定您希望它作为一个对象,外数组中没有字符串键会导致PHP猜测这是要带codeD作为JSON相当于阵列结构。

If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.

$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));

// Force the outer structure into an object rather than array
echo json_encode($arrytest , JSON_FORCE_OBJECT);

// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}

这篇关于多维数组给出不同的结果JSON_EN code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆