I have some data on a MySQL database representing a tree structure, and I want to convert it into JSON. I have used a recursive function to read all the data but I have no idea on how to convert into an array.
Here is the recursive function:
public function buildTree($parent, $level) {
// retrieve all children of $parent
$results = Department::all()->where('parent_id',$parent);
// display each child
foreach($results as $result)
{
echo $this->buildTree($result['id'], $level+1);
}
}
And the following is the JSON result I'd like to have in the end:
[
{
"id":1,
"text":"Root node",
"children":[
{
"id":2,
"text":"Child node 1",
"children":[
{
"id":4,
"text":"hello world",
"children":[{"id":5,"text":"hello world2"}]
}
]
},
{
"id":3,
"text":"Child node 2"
}
]
}
]