php 没有方括号json数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15559735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
no square bracket json array
提问by Curtis Crewe
When trying to access an API the JSON array must be parsed like this
尝试访问 API 时,必须像这样解析 JSON 数组
{"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);
it returns the json array without squared brackets as follows
它返回没有方括号的 json 数组,如下所示
{"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
我花了几个小时试图弄清楚如何解决这个问题,但想不出解决方案
回答by Jon
You need to wrap things in another array:
你需要把东西包装在另一个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:
如果我们使用等效的 PHP 5.4 数组语法,这将更容易理解:
$data = [ "item" => [ ["id" => "123456", "name" => "adam"] ] ];
Compare this with the JSON:
将此与 JSON 进行比较:
{ "item": [ {"id":"123456", "name":"adam" } ] }
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 documentationalready does so:
唯一需要解释的是为什么其中一个 PHP 数组仍然是[]JSON 中的数组,而另外两个则被转换为一个对象{}。但是文档已经这样做了:
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.
在对数组进行编码时,如果键不是从 0 开始的连续数字序列,则所有键都编码为字符串,并为每个键值对明确指定。
回答by Chad
Before reading this post, I had this:
在阅读这篇文章之前,我有这个:
echo json_encode($data);
echo json_encode($data);
After reading this post:
看完这篇文章后:
echo json_encode(array($data));
Brackets appeared on the start and end of the JSON object.
括号出现在 JSON 对象的开头和结尾。
:)
:)
回答by Dards
It become handy when using this way, so you can add more items on the array
使用这种方式会很方便,因此您可以在数组上添加更多项目
$val = array();
$val["id"]="123456";
$val["name"]="adam";
$data = array();
$data["item"][]=$val;
echo json_encode($data);
And it will ouput below:
它会在下面输出:
{"item":[{"id":"123456", "name":"adam"}]}
{"item":[{"id":"123456", "name":"adam"}]}
回答by Lietmotiv
Based on your code:
根据您的代码:
$data = array("item" => array("id" => "123456", "name" => "adam"));
echo json_encode($data);
You should just use another array() to force the bracket.
您应该只使用另一个 array() 来强制使用括号。
$data = array("item" => array(array("id" => "123456", "name" => "adam")));
echo json_encode($data);
This will return the value you are looking for:
这将返回您正在寻找的值:
{ "item": [ {"id":"123456", "name":"adam" } ] }

