willdanceforfun willdanceforfun - 21 days ago 5
PHP Question

I have a PHP multi dimensional associative array I want to convert into JSON that has an array and an object inside

I have a PHP array:

(
[username] => john
[attachments] => Array
(
[text] => hello
[color] => green
)

)


And I need to post it as JSON, so I know I can json_encode it and I get:

{"username":"john","attachments":{"text":"hello","color":"green"}}


But where I'm posting requires that 'attachments' comes through as a JSON object and not an array, like so:

{"username":"john","attachments":[{"text":"hello","color":"green"}]}


I could manually alter this string after I have encoded it and insert the '[' and ']' where needed, but is there another way?

Answer
$foo['attachments'] = [(object) $foo['attachments']];

Cast the array to an object, wrap in an array again, and then use json_encode on the result.