The arrays seen thus far have been single-dimensional, but ColdFusion also supports multidimensional arrays. To understand the need for multidimensional arrays, consider the previously used grocery list, which contains items but no quantities. To store a quantity along with each item (and maybe additional information), a two-dimensional array could be used. Two-Dimensional ArraysA two-dimensional array is similar to a grid, each item of which must be referenced by two indexes (the row and column). Index [1][1] would refer to row 1 and column 1, while [3][2] would refer to row 3, column 2. The following code defines a two-dimensional arraythink of it as a grid in which the left column contains the item and the right column contains the quantity: <!--- Grocery list ---> <cfset groceries = ArrayNew(2)> <cfset groceries[1][1] = "Bread"> <cfset groceries[1][2] = 3> <cfset groceries[2][1] = "Cheese"> <cfset groceries[2][2] = 2> <cfset groceries[3][1] = "Eggs"> <cfset groceries[3][2] = 12> <ul> <cfloop from="1" to="#ArrayLen(groceries)#" index="i"> <li> <cfoutput> #groceries[i][1]# - #groceries[i][2]# </cfoutput> </li> </cfloop> </ul> This code will loop through 3 times (the length of the array as returned by the ArrayLen() function). On each iteration, #groceries[i][1]# displays the item and #groceries[i][2]# displays the quantity. CAUTION When an array is two-dimensional, it must be referenced using both indexes. If the second index is omitted in <cfoutput>, an error occurs. Three-Dimensional ArraysColdFusion also supports three-dimensional arrays. To create a three-dimensional array, use: <cfset myarray=ArrayNew(3)> When using three-dimensional arrays, specific elements must be referenced using all three indexes: #myarray[2][3][2]# NOTE ColdFusion officially supports arrays of up to three dimensions, which is more than most developers will ever need. However, it is indeed possible to create even more complex multidimensional arrays by nesting arrays within arrays. |