我試圖組裝這個數據(樹結構)的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()
,但我不能找到一種方法,使嵌套對象工作。
我可以問你爲什麼這樣做,而不是'json_encode' – Baba
好喜歡我的問題說這個,我想不通的正常功能組裝PHP數組。這是迄今爲止我所得到的最接近的。但是,是的,我同意Php數組和josn_encode()最有意義 – djt