Nested Loops

Team-Fly    

ColdFusion® MX: From Static to Dynamic in 10 Steps
By Barry Moore
Table of Contents
Step 4.  Controlling Program Flow


It is possible to nest loops in a fashion similar to the way we nested IF statements. This can be a very useful feature. Look at the following code to see an example of nested loops used to dynamically build an HTML table.

 <!--- set the number of rows and columns --->  <CFSET Rows = 4>  <CFSET Cols = 5>  <!--- start the table outside the loop --->  <TABLE BORDER="1" CELLSPACING="0" CELLPADDING="1">     <!--- start outer loop --->     <CFLOOP INDEX="x" FROM="1" TO="#Rows#">        <!--- start row code --->        <TR>              <!--- start inner loop --->              <CFLOOP INDEX="y" FROM="1" TO="#Cols#">                    <!--- start code for columns --->                    <TD>                          <CFOUTPUT>Row #x#, Col #y#</CFOUTPUT>                    </TD>              </CFLOOP>        <!--- finish row code --->        </TR>     </CFLOOP>  <!--- finish the table --->  </TABLE>

After setting the values for the rows and columns of our table, we start an outer loop that begins the code for a table row. After that is complete, we drop into an inner loop that creates the code for our table cells by looping over some <TD> code. When the correct number of <TD> cells has been created (in this case, 5), we complete the inner loop and jump back into the outer loop. The outer loop finishes off the code for that row with a closing </TD> tag and loops back to the top to start all over again. This continues until the specified number of rows has been created.

Figure 4.6. Nested loop output.

graphics/04fig06.gif


    Team-Fly    
    Top
     



    ColdFusion MX. From Static to Dynamic in 10 Steps
    ColdFusion MX: From Static to Dynamic in 10 Steps
    ISBN: 0735712964
    EAN: 2147483647
    Year: 2002
    Pages: 140
    Authors: Barry Moore

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net