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"}
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"}]
You can get first element of parsed json. like this:
$json = '[{ "key1": "value1", "key2": "value2", "key3": "value3" }]';
$parse = json_decode($json,true);
echo json_encode($parse[0]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.