I’m trying to assemble this JSON object of Baobab data (tree structure). I have the following recursive function:
/* 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;
}
This is very close to working but as you see, there are no commas between each nested object and array, so the JSON is improperly formatted. Lots of the following:
… {"data":"Personal","attr": {"id" : "4"},"state":"closed","children": []}{"data":"News-editorial","attr": {"id" : "5"},"state":"closed","children": []…
I believe the best way would be to create a Php array and json_encode() it, but I can’t find a way to make the nested Objects work.
Well if you wanted to build this out through concatenation then just keep track of the first and subsequent elements. This modified code should work: