2

I want my json_encode to have a serialized string of:

 ['Element', 'Density', { role: 'style' }]

How do I do it?

I tried

   $data = array('Element', 'Density', "{ role: 'style' }");
   echo json_encode($data);

produces:

["Element","Density","{ role: 'style' }"]

Note the extra quotes

4
  • You need to use the regular syntax for array keys. Commented Oct 1, 2014 at 1:45
  • 1
    array('Element', 'Density', array('role' => 'style')); . Having a look at examples sometimes helps: php.net/manual/en/function.json-encode.php Commented Oct 1, 2014 at 1:46
  • you are trying to get an array that contains a dictionary, but you are inserting a string. Commented Oct 1, 2014 at 1:46
  • Note this is what you get when you mix keys with numerical indexes: codepad.org/aVsWPy5V Commented Oct 1, 2014 at 1:47

1 Answer 1

3

You nest it in another array:

$data = array('Element', 'Density', array('role' => 'style'));
                                  // ^ another nesting here
echo json_encode($data);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. It woks. I got thrown off because the nested array uses {} instead of [].
@Yada yeah, you really don't need to write it by hand, just construct a normal array structure, that json_encode() will handle that automatically
json_encode will by default treat PHP associative arrays as JSON objects, translating array keys into properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.