Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON Encode square bracket

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"]}
like image 304
Robert Dickey Avatar asked Mar 15 '26 08:03

Robert Dickey


1 Answers

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"]}
like image 165
Quentin Avatar answered Mar 17 '26 20:03

Quentin