2012-10-11 143 views
0

我試圖組裝這個數據(樹結構)的JSON對象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(),但我不能找到一種方法,使嵌套對象工作。

+0

我可以問你爲什麼這樣做,而不是'json_encode' – Baba

+0

好喜歡我的問題說這個,我想不通的正常功能組裝PHP數組。這是迄今爲止我所得到的最接近的。但是,是的,我同意Php數組和josn_encode()最有意義 – djt

回答

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; 
} 
+0

+1第一個元素的不錯觀察.. – Baba

+0

這似乎是工作迄今爲止,謝謝! – djt

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); 
+1

這比我的智能解決方案 –

+0

@Jason Sperske相信你可以改進它以達到你想要的效果...讓我知道如果你需要任何東西 – Baba

+0

不幸的是,這似乎並沒有工作。 '兒童'鍵沒有被填充,每個鍵都是空白的。並且只有1個級別的數組 – djt