|
||
ColdFusion TipsLooping through a 2D arraySo, you've figured out how to loop through a standard array. But what happens when you want to loop through a 2D array? How to you get to loop through all the indeces as well? And what if some elements of the array have more or less indeces than the others... ? Easy. Read on. <cfset MyArray = ArrayNew(2)>
<cfset MyArray[1][1] = 1> <cfset MyArray[1][2] = 2> <cfset MyArray[1][3] = 3> <cfset MyArray[1][4] = 4> <cfset MyArray[2][1] = 5> <cfset MyArray[2][2] = 6> <cfset MyArray[3][1] = 7> <cfset MyArray[3][2] = 8> <p>Array populated.</p> <cfloop index="OuterLoop" from="1" to="#ArrayLen(MyArray)#"> <cfloop index="InnerLoop" from="1" to="#ArrayLen(MyArray[OuterLoop])#"> <cfoutput> MyArray[#OuterLoop#][#InnerLoop#] is #MyArray[OuterLoop][InnerLoop]#<br> </cfoutput> </cfloop> </cfloop> <p>Loop complete.</p> First, we populated the array manually, giving some elements more indeces than others. Then we used cfloop to loop through the array ArrayLen(MyArray) times. In this example it will loop through the array 3 times, because it contains 3 elements. Then, using a nested cfloop, we loop through each element ArrayLen(MyArray[OuterLoop]) times. So, for the first element, 1 gets substitutded for OuterLoop and the InnerLoop loops through the element 1 of the array, in this instance 4 times. Then OuterLoop is incremented and we cfloop through the 2nd element of the array, and so on until all the elements have been cfoutputed. BooksI recommend getting Ben Forta's ColdFusion Web Application Construction Kit (currently at 3rd edition - ISBN 0-7897-1809-X). I can't say enough good things about this book, except that the chapter on Session and Client variables (ch 26) is appalling compared to the rest of it. And that's why you're also going to have to buy... Arman Danesh's Mastering Coldfusion 4 from Sybex (ISBN 0-7821-2452-6). Pound for pound, it's not quite as good as CFWACK, but it's chapter on Session and Client variables is excellent and it also goes further into the more advanced ColdFusion topics. Ben Forta also covers those advanced aspects, but you have to buy his second book, Advanced CFWACK, to find out what they are. Mailing listsFor ColdFusion, there is only one mailing list worth mentioning - CF-Talk. Subscribe at The House Of Fusion. High traffic, helpful people - 'nuff said. |
||
|
||