When trying to access an API the JSON array must be parsed like this

{"item":[{"id":"123456", "name":"adam"}]}

But when i'm doing the following code

$data = array("item" => array("id" => "123456", "name" => "adam"));
echo json_encode($data);

它返回不带方括号的json数组,如下所示

{"item":{"id":"123456","name":"adam"}}

我花了几个小时想办法解决这个问题,就是想不出解决办法

推荐答案

You need to wrap things in another array:

$data = array("item" => array(array("id" => "123456", "name" => "adam")));

This will be more understandable if we use the equivalent PHP 5.4 array syntax:

$data = [ "item" => [ ["id" => "123456", "name" => "adam"] ] ];

Compare this with the JSON:

        { "item":   [ {"id":"123456", "name":"adam"      } ] }

唯一要解释的是为什么其中一个PHP数组在JSON中保持为数组[],而其他两个则转换为对象{}.但documentation强已经这么做了:

在对数组进行编码时,如果键不是连续的数字 从0开始的序列,所有键都编码为字符串,并且 for each 键-值对显式指定.

Json相关问答推荐

如何使用Laravel在MariaDB JSON kolumn中使用unicode字符

如何在Power BI中集成API和JSON数据后将数据转换为表?

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

如何在VegaLite中应用Times New Roman,CaliBiri字体

使用JQ将JSON输出转换为CSV复杂 struct

无法访问id的第三级json

如何使用 JOLT 将带有列表的 JSON 项目取消列出为多个项目?

JQuery,使用 GET 方法发送 JSON 对象

如何将任意 json 对象发布到 webapi

按 JSON 数据类型 postgres 排序

apple-app-site-association json 文件是否会在应用程序中更新?

Spring Security 和 JSON 身份验证

json_encode() 返回 false

如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

在 React 中访问子级的父级状态

我可以使用空字符串作为对象标识符吗?

如何使用 Serde 反序列化带有自定义函数的可选字段?

为什么 JavaScript 的 eval 需要括号来判断 JSON 数据?

春天:返回@ResponseBodyResponseEntity>

如何从 MySQL 中检索 JSON 数据?