I wanna json encode a PHP array to send it for a server, but the server wants it in this format:
[{ "key1": "value1", "key2": "value2", "key3": "value3" }]
But now my associative array after using json_encode() on it looks like this:
{ "key1": "value1", "key2": "value2", "key3": "value3"}
Advertisement
Answer
The first version with the []
is an array of objects, you just have a single object. Just create an array with that single object…
echo json_encode( [ $data ] );
gives…
[{"key1":"value1","key2":"value2","key3":"value3"}]