Ok. Line by line.
Initialize the 'root' of my tree.
Code:
while($row = fetch_row($result)) {
this is a Foreach on the resultset.
Code:
$out[$row['category_id']] = ucfirst($row['category_name']);
Define the node within the node array. ucfirst makes the first letter capital.
Code:
$children[$row['parent_id']][] = $row['category_id'];
Inside the children array, this node's parent has a new child (this node.) Note that top level elements dont actually have a defined parent(ID: 0 does not exist in your record set.), so the root node is defined in the first line.
Endforeach and start recurse to walk the tree from the root node (0).
Code:
function recurse($id,$prefix = "") {
Define function recurse. Required Parameter $id, Optional Parameter $prefix (default = null).
Code:
global $out,$children;
Gonna need my arrays for referencing.
Code:
echo $prefix.$out[$id];
Echo out the current element. (For 0, this will echo nothing, as both $prefix and $out[0] are null.)
Code:
foreach($children[$id] AS $child) {
For each child of the current node
Code:
recurse($child,$prefix." ");
call this function using the child's ID and add a space character to the existing $prefix.
EndForeach, EndFunction.
Now, as to solving the undefined index, add this to the while loop after putting the child in the parent's node.
PHP Code:
$children[$row['category_id']] = array();
Bookmarks