stack
stack

Reputation: 10228

How can I make a nested array tree into an nested object tree?

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?

Upvotes: 1

Views: 107

Answers (2)

Ofir Baruch
Ofir Baruch

Reputation: 10346

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

Upvotes: 2

Boris D. Teoharov
Boris D. Teoharov

Reputation: 2388

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()]);
[{},{}]

Upvotes: 1

Related Questions