Search code examples
phpfor-looprecursionnested-loopsfamily-tree

Which function can replace multiple nested loops in php?


I work on a family-tree function, and I need to iterate a for() statement for each generation.

I don't know the number of generation in advance and all for() statements will contain almost the same script...

$nb_parents_line1 = 1;
for($i = 0 ; $i < $nb_parents_line1 ; $i++) {

    $nb_parents_line2 =  $nb_son[$i];
    for($i2 = 0 ; $i2 < $nb_parents_line2 ; $i2++) {/*for each son of each parent*/

        $nb_parents_line3 = ;
        for($i3 = 0 ; $i3 < $nb_parents_line3 ; $i3++) {/*for each son of each son of each parent*/

            $nb_parents_line4 = ;
            for($i4 = 0 ; $i4 < $nb_parents_line4 ; $i4++) {/*and so on...*/

            }
            /*center*/
        }
    /*code for center*/
    }
/*code for center*/
}

Is there a easiest way to do such a two dimensional for ? Is there a way for having just as for() as I need ?


Solution

  • Finally I used/adapted the suggestion of user2182349 :

    $level_max = 4;
    
    function recursive_function($level) {
    
        global $i, $nb_parents_line, $levelmax;
    
        $tmp = $nb_parents_line[$level]; //The number of child per parents : the index represent the generation
    
        //code to execute before going down a level
    
        for($i[$level] = 0; $i[$level] < $tmp; $i[$level]++) {
    
            if($level < $level_max){
    
                recursive_function($level +1); //level +1
            }
    
        }
    
        //code to exectute after the script had gone down all levels and reup levels one by one
    }
    

    This actual code will execute the deepest for() statement first, that allow in this case to know exactly the width of all children before calculating width of the parent. But you can change the order by putting any code before the for().