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

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

问题描述

在 PHP 中对多维数组执行 json_encode 时,我注意到只是通过命名其中一个数组而不是不命名它们会产生不同的输出.例如:

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)

创建一个包含多个 json 对象的单个 json 对象

creates a single json object with multiple json objects inside

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

为什么第一个选项不会返回与第二个执行相同的结果,用1"代替secondarray"

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 假定它被编码为 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_ENCODE 给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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