php中作为树格式的Json数组

php中作为树格式的Json数组,php,arrays,json,Php,Arrays,Json,我有这个php代码来形成层次结构 $arr = array( 'name' => "Level 2: A", 'parent' => "Top Level", 'children' => "" ); $arr2 = array( 'name' => "Top Level", 'parent' => "null", 'children' => "$arr" ); echo json_encode($ar

我有这个php代码来形成层次结构

    $arr = array(
    'name' => "Level 2: A",
    'parent' => "Top Level",
    'children' => ""
);

$arr2 = array(
    'name' => "Top Level",
    'parent' => "null",
    'children' => "$arr"
);

echo json_encode($arr2);
但是我无法访问JSON输出中的数组

我的JSON输出:{“name”:“Top-Level”,“parent”:“null”,“children”:“Array”}

我的目标是创建一个这样的数组,但是使用JSON,但是它返回的是
数组
,而不是
数组中的数据

var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
  {
     "name": "Level 2: A",
     "parent": "Top Level",
     "children": [
      {
        "name": "Son of A",
        "parent": "Level 2: A"
      },
      {
        "name": "Daughter of A",
        "parent": "Level 2: A"
      }
    ]
  },
  {
    "name": "Level 2: B",
    "parent": "Top Level"
  }
]
}
];

你必须记住关于$arr

$arr2 = array(
    'name' => "Top Level",
    'parent' => "null",
    'children' => $arr // <- remove quotes here
);
这将使您的代码保持一致,因为您总是在
children
属性下有一个数组。

为什么
children=>“$arr”
??应该是
'children'=>数组($arr)
'children'=>$arr
$arr = array(
    'name' => "Level 2: A",
    'parent' => "Top Level",
    'children' => array() // <- here
);