User Guide
122 Chapter 8 Handling Complex Data with Structures
Using nested loops for 2D and 3D arrays
To output values from 2D and 3D arrays, you must employ nested loops to return
array data. With a 1D array, a single
cfloop is sufficient to output data, as in the
previous example. With arrays of dimension greater than one, you need to maintain
separate loop counters for each array level.
Nesting cfloops for a 2D array
The following example shows how to handle nested cfloops 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 CFLOOPs for a 3D array
For 3D arrays, you simply nest an additional cfloop. (This example does not set the
array values first. You can try doing it as an exercise.)
<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>