PHP JSON Encode square bracket

Robert Dickey picture Robert Dickey · Mar 11, 2016 · Viewed 7k times · Source

I have a simple JSON array I am trying to encode. Inside of the JSON string I need another array in square brackets. I am unable to figure out how to make the internal brackets square. Any advice?

Here is my code

$data = [ "item" =>  ["id" => "123456", "name" => "adam"]  ];                                                                    
$data_string = json_encode($data);

Here is the output

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

What I am hoping to get

{"item":["1123","1134","1184"]}

Answer

Quentin picture Quentin · Mar 11, 2016

In JSON [] is an array and {} is an object.

An array holds an ordered list of values.

An object holds an unordered group of key / value pairs.

If you want an array, then you have to provide an ordered list of values (a PHP array) and not a set of key / value pairs (a PHP associative array).


$data = [ "item" =>  ["id", "123456", "name", "adam"]  ];
$data_string = json_encode($data);

gives

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