0

我正在尝试组装这个猴面包树数据的 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 格式不正确。以下很多:

... { "data":"Personal","attr": {"id" : "4"},"state":"closed","children": []}{"data":"News-editorial","attr": {"id" : "5"},"state":"closed","children": []...

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

4

2 回答 2

1

你可以像这样安抚

$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);
于 2012-10-11T16:46:01.210 回答
1

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

/* 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;
}
于 2012-10-11T16:46:17.653 回答