如何将嵌套数组树嵌入到嵌套对象树中?

时间:2017-01-29 12:37:22

标签: php arrays

这是我的代码:

$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));

这是上面代码的结果:

enter image description here

如您所见,data的值为[],而我想要此{}。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

虽然我不确定你的问题背后的原因是什么, 而不是将data键设置为数组,只需将其定义为新对象

$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));

<强>来源:

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

答案 1 :(得分:1)

如果它适合你(或stdClass),你可以使用ArrayObject。

PHP Manual for ArrayObject

例如:

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