willdanceforfun willdanceforfun - 2 years ago 60
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:


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


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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download