ColdFusion 9.0 Resources |
Populating an array with the cfloop tagThe cfloop tag provides a common and efficient method for populating an array. The following example uses a cfloop tag and the MonthAsString function to populate a simple 1D array with the names of the months. A second cfloop outputs data in the array to the browser. <cfset months=arraynew(1)> <cfloop index="loopcount" from=1 to=12> <cfset months[loopcount]=MonthAsString(loopcount)> </cfloop> <cfloop index="loopcount" from=1 to=12> <cfoutput> #months[loopcount]#<br> </cfoutput> </cfloop> Using nested loops for 2D and 3D arraysTo output values from 2D and 3D arrays, employ nested loops to return array data. With a one-dimensional (1D) array, a single cfloop is sufficient to output data, as in the previous example. With arrays of dimension greater than one, you maintain separate loop counters for each array level. Nesting cfloop tags for a 2D arrayThe following example shows how to handle nested cfloop tags to output data from a 2D array. It also uses nested cfloop tags to populate the array: <cfset my2darray=arraynew(2)> <cfloop index="loopcount" from=1 to=12> <cfloop index="loopcount2" from=1 to=2> <cfset my2darray[loopcount][loopcount2]=(loopcount * loopcount2)> </cfloop> </cfloop> <p>The values in my2darray are currently:</p> <cfloop index="OuterCounter" from="1" to="#ArrayLen(my2darray)#"> <cfloop index="InnerCounter" from="1"to="#ArrayLen(my2darray[OuterCounter])#"> <cfoutput> <b>[#OuterCounter#][#InnerCounter#]</b>: #my2darray[OuterCounter][InnerCounter]#<br> </cfoutput> </cfloop> </cfloop> Nesting cfloop tags for a 3D arrayFor 3D arrays, you simply nest an additional cfloop tag. (This example does not set the array values first to keep the code short.) <cfloop index="Dim1" from="1" to="#ArrayLen(my3darray)#"> <cfloop index="Dim2" from="1" to="#ArrayLen(my3darray[Dim1])#"> <cfloop index="Dim3" from="1"to="#ArrayLen(my3darray[Dim1][Dim2])#"> <cfoutput> <b>[#Dim1#][#Dim2#][#Dim3#]</b>: #my3darray[Dim1][Dim2][Dim3]#<br> </cfoutput> </cfloop> </cfloop> </cfloop> |