38

When trying to access an API the JSON array must be parsed like this

{"item":[{"id":"123456", "name":"adam"}]}

But when i'm doing the following code

$data = array("item" => array("id" => "123456", "name" => "adam"));
echo json_encode($data);

it returns the json array without squared brackets as follows

{"item":{"id":"123456","name":"adam"}}

I've spent hours trying to figure out how to fix this and just can't think of a solution

3 Answers 3

75

You need to wrap things in another array:

$data = array("item" => array(array("id" => "123456", "name" => "adam")));

This will be more understandable if we use the equivalent PHP 5.4 array syntax:

$data = [ "item" => [ ["id" => "123456", "name" => "adam"] ] ];

Compare this with the JSON:

        { "item":   [ {"id":"123456", "name":"adam"      } ] }

The only thing to explain is why one of the PHP arrays remains an array [] in JSON while the other two get converted to an object {}. But the documentation already does so:

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

Sign up to request clarification or add additional context in comments.

2 Comments

When using that code as provided it's placing the squared brackets outside everything instead of inside item ?
@CurtisCrewe: Sorry, typo. Fixed now.
9

Before reading this post, I had this:

echo json_encode($data);

After reading this post:

echo json_encode(array($data));

Brackets appeared at the start and end of the JSON object.

1 Comment

Useful, but if you want the brackets IN the data arrays, just use something like this: $MyArray = array( "something" => [array("foo" => "bar")] );
3

It become handy when using this way, so you can add more items on the array

$val = array();
$val["id"]="123456";
$val["name"]="adam";

$data = array();
$data["item"][]=$val;

echo json_encode($data);

And it will ouput below:

{"item":[{"id":"123456", "name":"adam"}]}

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.