1

Here is my code:

$adjacencies = array (  "0" => array(   "name1" => "pear",
                                        "name2" => "jack",
                                        "data" => array()   ),
                        "1" => array(   "name1" => "pear",
                                        "name2" => "john",
                                        "data" => array()   )
                    );

$final_array['adjacencies'] = $adjacencies;
echo "<pre>";
print_r(json_encode($final_array));

And this is the result of code above:

enter image description here

As you see data's value is [], while I want this {} instead. How can I do that?

1

2 Answers 2

2

While I'm not sure what's the reason behind your question, instead of setting the data key as an array, simply define it as a new object.

$adjacencies = array (  "0" => array(   "name1" => "pear",
                                        "name2" => "jack",
                                        "data" => new stdClass()   ),
                        "1" => array(   "name1" => "pear",
                                        "name2" => "john",
                                        "data" => new stdClass()   )
                    );

$final_array['adjacencies'] = $adjacencies;
echo "<pre>";
print_r(json_encode($final_array));

Source:

http://php.net/manual/en/language.types.object.php#107071

Sign up to request clarification or add additional context in comments.

Comments

1

You could use ArrayObject if it suits you (or stdClass).

PHP Manual for ArrayObject

For example:

php > echo json_encode([[],[]]);
[[],[]]
php > echo json_encode([ new ArrayObject(), new ArrayObject()]);
[{},{}]

Comments

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.