I've looked around the internet and haven't quite found what I'm looking for. I have a flat array with each element containing an 'id' and a 'parent_id'. Each element will only have ONE parent, but may have multiple children. If the parent_id = 0, it is considered a root level item. I'm trying to get my flat array into a tree. The samples I have found only working for core php. Because in codeigniter recursive is not qorking
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['id']] = $element;
unset($elements[$element['id']]);
}
}
return $branch;
}
My Flat array is
Array
(
[1] => Array
(
[id] => 1
[parent_id] => 0
[permission_category] => Listing
[3] => Array
(
[id] => 3
[parent_id] => 1
[permission_category] => Tour
)
[4] => Array
(
[id] => 4
[parent_id] => 1
[permission_category] => Activity
)
[12] => Array
(
[id] => 12
[parent_id] => 0
[permission_category] => Bookings
[parent_permission_category] =>
)
[13] => Array
(
[id] => 13
[parent_id] => 12
[permission_category] => Activity Bookings
)
[14] => Array
(
[id] => 14
[parent_id] => 12
[permission_category] => Tour Bookings
)
);
It is only showing one parent children
Array
(
[1] => Array
(
[id] => 1
[parent_id] => 0
[permission_category] => Listing
[children] => Array
(
[3] => Array
(
[id] => 3
[parent_id] => 1
[permission_category] => Tour
)
[4] => Array
(
[id] => 4
[parent_id] => 1
[permission_category] => Activity
)
)
)
)