I\'m looking to write a function that takes an array of pages/categories (from a flat database result) and generates an array of nested page/category items based on the pare
Some very simple, generic tree building:
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);
The algorithm is pretty simple:
0
/nothing/null
/whatever).parent_id
of an element matches the current parent id you got in 1., the element is a child of the parent. Put it in your list of current children (here: $branch
).children
element.In other words, one execution of this function returns a list of elements which are children of the given parent id. Call it with buildTree($myArray, 1)
, it will return a list of elements which have the parent id 1. Initially this function is called with the parent id being 0, so elements without parent id are returned, which are root nodes. The function calls itself recursively to find children of children.