没有方括号json数组 [英] no square bracket json array

查看:649
本文介绍了没有方括号json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试访问API时,必须像这样解析JSON数组

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数组,如下所示:

it returns the json array without squared brackets as follows

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

我花了数小时试图找出解决方法,却想不出解决办法

I've spent hours trying to figure out how to fix this and just can't think of a solution

推荐答案

您需要将内容包装在另一个array中:

You need to wrap things in another array:

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

如果我们使用等效的PHP 5.4数组语法,这将更容易理解:

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

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

将此与JSON进行比较:

Compare this with the JSON:

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

唯一要说明的是为什么一个PHP数组在JSON中仍然是数组[],而另两个数组被转换为对象{}.但是文档已经这样做了:

The only thing to explain is why one of the PHP arrays remains an array [] in JSON while the other two get converted to an object {}. But the documentation already does so:

对数组进行编码时,如果键不是连续数字 从0开始的序列,所有键都编码为字符串,并且 为每个键值对明确指定.

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

这篇关于没有方括号json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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