简体   繁体   中英

foreach loops with dynamic number of loops

Currently I am looping through 4 foreach loops:

foreach ($level0_array as $level0_key => $level1_array) {
    //do something
    foreach ($level1_array as $level1_key => $level2_array) {
        //do something
        foreach ($level2_array as $level2_key => $level3_array) {
            //do something
            foreach ($level3_array as $level3_key => $level4_value) {
                //do something
            }
        }
    }
}

Is it possible to do it if this loop is inside a function and it is supposed to get the number of levels to loop through dynamically? (Assuming in this case that $level0_array have enough levels in it)

ie

function ($level0_array, $number_of_levels) {
    // loop. . .
}

Yes, there is, and it is called recursion :

function loopThroughLevels($level_array, $number_of_levels_left) {
     foreach ($level_array as $level_key => $level_value) {
         // do something
         if (is_array($level_value) &&
             ($number_of_levels_left > 0)) {
             loopThroughLevels($level_value, $number_of_levels_left - 1);
         }
     }
}

Here the function calls itself again, looping through a sub-level of the array as long as there is an array to loop through and there are levels left you want to loop through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM