首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >组装多维JSON对象

问组装多维JSON对象
EN

Stack Overflow用户
提问于 2012-10-12 00:39:15
回答 2查看 190关注 0票数 0

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

代码语言:javascript
复制
/* 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(),但是我找不到一种方法来使嵌套对象工作。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-12 00:46:18

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

代码语言:javascript
复制
/* 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;
}
票数 1
EN

Stack Overflow用户

发布于 2012-10-12 00:46:01

你可以像这样舒缓情绪

代码语言:javascript
复制
$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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12844434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档