向JSON数组中添加JSON对象


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

EDIT(编辑我以前的问题):

首先,我想要的结果不是一个有效的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]]}