使用 PHP 创建 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20382369/
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
Create JSON object using PHP
提问by d_raja_23
How can I achieve or create this type JSON object using PHP?
如何使用 PHP 实现或创建这种类型的 JSON 对象?
{
"label": "Devices per year",
"data": [
[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]
]
}
After several attempt I didn't find the solution. For example I tried this:
经过多次尝试,我没有找到解决方案。例如我试过这个:
$arrayDateAndMachine = array(
"1999"=>3.0,
"2000"=>3.9
);
$arr = array(
"label" => "Devices per year",
"data" => $arrayDateAndMachine
);
var_dump(json_encode($arr));
回答by V G
$obj = new stdClass();
$obj->label="Devices per year";
$obj->data = array(
array('1999','3.0'),
array('2000','3.9'),
//and so on...
);
echo json_encode($obj);
回答by A.M.N.Bandara
Try using this
尝试使用这个
$arrayDateAndMachine = array( array("1999","3.0"),
array("2000","3.9")
);
回答by adam187
square brackets []in jsonis array so you have to do it like this
方括号[]中json是数组,所以你必须做这样的
<?php
$arrayDateAndMachine = array(
array(1999, 3.0),
array(2000, 3.9),
);
$arr = array("label" => "Devices per year",
"data" => $arrayDateAndMachine);
var_dump(json_encode($arr));
回答by Nik
I prefer the following syntax which gets the desired result and is clear to read:
我更喜欢以下语法,它可以获得所需的结果并且易于阅读:
$ar = array(
"label" => "Devices per years",
"data" => array(array(1999, 3.0), array(2000, 3.9) )
);
var_dump(json_encode($ar));
The only difference being that in the output "3.0" is rendered as "3". If you need the trailing ".0" you could surround those values with quotes.
唯一的区别是在输出“3.0”中呈现为“3”。如果您需要尾随的“.0”,您可以用引号将这些值括起来。
回答by surrealcoder
Doing something like this should work if you would like to declare it as JSON only and not by using json_encode. This also eliminates the need to declare multiple variables for each of the arrays inside. But this would be a viable solution only if the contents of the array for data is finite.
如果您只想将其声明为 JSON 而不是使用 json_encode,那么这样做应该可以工作。这也消除了为内部的每个数组声明多个变量的需要。但是,只有当数据数组的内容是有限的时,这才是一个可行的解决方案。
$json_string = '{
"label": "Devices per year",
"data": [
[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]
]}';

