0

このBaobabデータの 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 に答える