[英]Adding JSON Objects to JSON Array
例如,如果我做这样的事情:
<?php
//first json object
$cars[] = "1";
$cars[] = "2";
$cars[] = "3";
$cars[] = "4";
//second json object
$cars[] = "22";
$cars[] = "33";
$cars[] = "44";
$cars[] = "55";
//now i need to add them to the json array "cars"
echo json_encode(array("cars" => $cars));
?>
输出将变为:
{"cars":["1","2","3","4"]}
但是,我希望它是:
{
"cars": [
{"1", "2", "3", "4"},
{"22", "33", "44", "55"}
]
}
编辑 (编辑我的旧问题):
首先,我想要的结果不是有效的JSON。
它必须是这样的:
{
"cars": [
["1", "2", "3", "4"],
["22", "33", "44", "55"]
]
}
为了获得上述结果,只需执行以下操作:
整个代码:
<?php
// Add the first car to the array "cars":
$car = array("1","2","3","4");
$cars[] = $car;
// Add the second car to the array "cars":
$car = array("22","33","44","55");
$cars[] = $car;
//Finally encode using json_encode()
echo json_encode(array("cars" => $cars));
?>
这是使用有效JSON可获得的最接近的结果:
$cars[] = array("1","2","3","4");
$cars[] = array("22","33","44","55");
echo json_encode(array("cars" => $cars));
//{"cars":[["1","2","3","4"],["22","33","44","55"]]}
$cars[] = (object) array("1","2","3","4");
$cars[] = (object) array("22","33","44","55");
echo json_encode(array("cars" => $cars));
//{"cars":[{"0":"1","1":"2","2":"3","3":"4"},{"0":"22","1":"33","2":"44","3":"55"}]}
在JSON中, []
是索引数组,例如: array(1,2,3)
而{}
是一个关联数组,例如: array('one'=>1, 'two'=>2, 'three'=>3)
您在示例中指定的语法无效。 您将获得的最接近的是:
echo json_encode(array(
'cars'=>array(
array(1,2,3,4),
array(11,22,33,44)
)
));
//output: {"cars":[[1,2,3,4],[11,22,33,44]]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.