Php 组装多维JSON对象

Php 组装多维JSON对象,php,json,Php,Json,我正在尝试组装这个JSON数据对象(树结构)。我有以下递归函数: /* Takes the Tree (in this case, always '1') and the Parent ID where we want to start, this case, I would also start with '1' */ function walkTree($tree, $id) { /* Gets the children of that of that ID */ $ch

我正在尝试组装这个JSON数据对象(树结构)。我有以下递归函数:

/* Takes the Tree (in this case, always '1') and the Parent ID where we want to start, this case, I would also start with '1' */
function walkTree($tree, $id)
{
     /* Gets the children of that of that ID */
     $children = $tree->getChildren($id);

     $data = "";

     /* Loop through the Children */
     foreach($children as $index => $value) 
     {
          /* A function to get the 'Name' associated with that ID */
          $name = getNodeName($tree, $value);

          /* Call the walkTree() function again, this time based on that Child ID */
          $ret = walkTree($tree, $value);

          /* Append the string to $data */
          $data .= '{"data":"'.$name.'","attr": {"id" : "'.$value.'"}
                   ,"state":"closed","children": ['.$ret.']}';
     }

     /* Return the final result */
     return $data;
}
这非常接近于正常工作,但正如您所看到的,每个嵌套对象和数组之间没有逗号,因此JSON的格式不正确。以下是很多:

。。。{
“数据”:“个人”,“属性”:{“id”:“4”},“状态”:“已关闭”,“子项”:[]}{“数据”:“新闻社论”,“属性”:{“id”:“5”},“状态”:“已关闭”,“子项”:[]


我相信最好的方法是创建一个Php数组并
json_encode()
它,但我找不到一种方法使嵌套对象工作。

你可以用这样的方法来代替

$data = array();

foreach($children as $index => $value)
{
    $node = array();
    $node['data'] = getNodeName($tree, $value) ;
    $node['attr'] = array("id"=>$value,"state"=>"closed","children"=>walkTree($tree, $value)) ;

    $data[] = $node ;
}

return json_encode($data);

如果您想通过串联来构建此代码,那么只需跟踪第一个和后续元素即可。此修改后的代码应该可以工作:

/* Takes the Tree (in this case, always '1') and the Parent ID where we want to start, this case, I would also start with '1' */
function walkTree($tree, $id)
{
  /* Gets the children of that of that ID */
  $children = $tree->getChildren($id);
  $first = true;

  $data = "";

  /* Loop through the Children */
  foreach($children as $index => $value) 
  {
    /* A function to get the 'Name' associated with that ID */
    $name = getNodeName($tree, $value);

    /* Call the walkTree() function again, this time based on that Child ID */
    $ret = walkTree($tree, $value);

    /* Append the string to $data */
    if($first) {
       $first = false;
    } else {
      /*add comma for each element after the first*/
      $data .= ',';
    }
    $data .= '{"data":"'.$name.'","attr": {"id" : "'.$value.'"},"state":"closed","children": ['.$ret.']}';
  }

  /* Return the final result */
  return $data;
}

我可以问你为什么要这样做,而不是像我在问题中说的那样,我无法找到正确的函数来组装Php数组。这是迄今为止我得到的最接近的结果。但是,是的,我同意Php数组和josn_encode()最有意义这是一个比mine@JasonSperske我相信你可以改进它来实现你想要的…如果你还需要什么,请告诉我。幸运的是,这似乎不起作用。没有填充“children”键,每个键都是空白的。而且,只有一个级别array@dtj工作wi数据有限..不知道$tree是什么样子