Php 向JSON数组添加JSON对象
例如,如果我做了这样的东西:Php 向JSON数组添加JSON对象,php,json,Php,Json,例如,如果我做了这样的东西: <?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_e
<?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"],
["22", "33", "44", "55"]
]
}
然而,我希望它是:
{
"cars": [
{"1", "2", "3", "4"},
{"22", "33", "44", "55"}
]
}
编辑(编辑我的旧问题):
首先,我想要的结果不是有效的JSON
它必须是这样的:
<?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"],
["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中,[]是一个索引数组,例如:
数组(1,2,3)
而{}
是一个关联数组,例如:数组('1'=>1,'2'=>2,'3'=>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]]}
这不是有效的JSON。此外,还不清楚你是如何想出那篇
{“22”、“33”、“44”、“55”}
文章的。