Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.7. Multidimensional Arrays

You want to create an array with more than one dimension.

Technique

Use ArrayNew(), passing in as a parameter the number of dimensions you require, to create a multidimensional array.









<!---Create a two dimensional aBeachBoysAlbums array--->
<cfset aBeachBoysAlbums = ArrayNew(2)>

<!---Build first album array, Surfin' Safari--->
<cfset aBeachBoysAlbums[1][1] = "Surfin' Safari">
<cfset aBeachBoysAlbums[1][2] = "County Fair">
<cfset aBeachBoysAlbums[1][3] = "Ten Little Indians">

<!---Build second album array, Surfin' USA--->
<cfset aBeachBoysAlbums[2][1] = "Surfin' USA">
<cfset aBeachBoysAlbums[2][2] = "Farmer's Daughter">
<cfset aBeachBoysAlbums[2][3] = "Miserlou">

<!---Build third album array, Surfer Girl--->
<cfset aBeachBoysAlbums[3][1] = "Surfer Girl">
<cfset aBeachBoysAlbums[3][2] = "Catch a Wave">
<cfset aBeachBoysAlbums[3][3] = "The Surfer Moon">

Comments

A multidimensional array is an array of arrays rather than an array of single values. Until this point in the chapter, one-dimensional arrays have been covered, and the array elements have all been simple values—the name of a song or a letter of the alphabet. In a multidimensional array, you use the array elements to store other arrays.

ColdFusion allows you to define up to three dimensions in an array with a call to the ArrayNew() function. ArrayNew() takes one argument—1, 2, or 3—depending on how many dimensions you need.

This code is an example of creating a two-dimensional array. It continues using the Beach Boys as a model and uses a two-dimensional array to store album information in order of release. For this example, you use only the first three songs from each of their first three releases.

If you want to display the values stored in the inner dimensions of an array, it is necessary first to get a handle on each element. Using cfloop is the best way to do so. Remember, you need exactly as many loops as you have dimensions in the array.

  • + Share This
  • 🔖 Save To Your Account