0

For example, if I make something like this:

<?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));

?>

The output will become :

{"cars":["1","2","3","4"]}

However, I want it to be:

     {
    "cars": [
        {"1", "2", "3", "4"},
        {"22", "33", "44", "55"}
    ]
     }

EDIT (editing my old questions):

First of all, the result i wanted is not a valid JSON.

It has to be something like this:

  {
    "cars": [
        ["1", "2", "3", "4"],
        ["22", "33", "44", "55"]
    ]
 }

In order to get the above result, simply do the following:

The entire code:

<?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));
?>
1
  • 5
    That's not valid JSON. Furthermore, it's not clear at all how you came up with that {"22","33","44","55"} piece. Commented Mar 14, 2014 at 18:06

2 Answers 2

1

Here's the closest you can get with valid 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"}]}
Sign up to request clarification or add additional context in comments.

Comments

0

In JSON [] is an indexed array, eg: array(1,2,3)

and {} is an associative array, eg: array('one'=>1, 'two'=>2, 'three'=>3)

The syntax you've specified in your example is invalid. The closest you're going to get is:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.