Hi All,
I am looking for some advice on a recursive method I am trying to add into a resource controlled to return flat SQL data in a tree like format for the backend.
I am aware this has been posted before as I have used one post but it does not seem to work for me as follows is my data and desired output :-
id parent_id text
1 0 Parent
2 1 Child
3 2 Grandchild
4 0 Parent 2
5 4 Child 2
5 1 Child
Tree Required :-
Parent
– Child
— Grandchild
– Child
Parent 2
– Child 2
I did try the following post and suggestion from [@bobbybouwmann] :-
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($rows);
My data array is passing to the method fine and I can dd the elements right up until $children when I try to re use the method. The result of $branch is an empty array.
I understand how this is meant to work but am a little puzzled as to why I get an empty data set. I am happy if it is an array of data or collection preferably a collection.
As I do not have a limit or cannot foresee how deep the tree may go I wanted to make a dynamic loop of the table so I could output this in order in nested ‘ul’ containers so it would work regardless of the depth.
Pretty sure someone will have done something similar to the above just wondering anyone else’s thoughts on this and if they have experienced similar issues.
Thanks in advance Jamie