将JSON对象添加到JSON数组

时间:2014-03-14 18:05:32

标签: 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_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));
?>

2 个答案:

答案 0 :(得分:1)

这是您使用有效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"}]}

答案 1 :(得分:0)

在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]]}