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"]}
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"]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With