Question

I am learning how to build a parent/child category list. I found a great tutorial and have implemented the following code:

while($row = $tree_sth->fetch()){
    $rows[$row['id']] = array('name'=>$row['name'], 'on'=>$row['on'], 'parent'=>$row['parent']);
}

function btree($parent){

    $has_childs = false;
    global $rows;

    foreach ($rows as $key => $value){
        if($value['parent'] == $parent){
            if ($has_childs === false){
                $has_childs = true;
                echo '<ul>';
            }
            echo '<li>'.$value['name'];
            btree($key);
            echo '</li>';
        }
    }
    if($has_childs === true){
        echo'</ul>';
    }
}

What I am having trouble understanding is how the foreach and recursive function is handled by PHP.

It appears that this causes multiple "instances??" of the function and foreach loop to run simultaneously... Is that correct?

If this is what is happening, it seems this may slow down as my list grows and child relationships get deeper. Is this true?

Was it helpful?

Solution

The short, short version is that the function is working this way:

Begin-function (first instance):
     Begin-loop:
          Loop...
          Begin-func-again?

               Begin-function (second instance):
                   Begin-loop:
                        Loop... 
                        Begin-func-again?

                             Begin-function (third instance):
                                  Begin-loop:
                                      Loop...
                                      Begin-func-again? (NO)
                                          // termination point reached
                                  End-loop
                             End-function (third instance)

                    End-loop (from second instance)
               End-function (second instance)

     End-loop (from first instance)
End-function(first instance)

It isn't that there are multiple versions of the function being created simultaneously, they are an expansion and contraction done in order, but they all do stem from the original function call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top