Using Structures as Associative Arrays  
 
 

You can also use structures as associative arrays. Structures index data by string keys rather than by integers.

You might use structures to create an associative array that matches people's names with their departments. In this example, a structure named Departments includes an employee named John, listed in the Sales department. To access John's department, you would use the syntax, Departments["John"].

A structure's key must be a string. The values associated with the key can be anything:

  • a string
  • an integer
  • an array
  • another structure
 
 
  Looping through structures  
 
 

The following example shows how you can loop through a structure to output its contents. Note that when you enumerate key-value pairs using a loop, the keys appear in upper-case.

<!--- Create a structure and loop through its contents --->

<CFSET Departments=StructNew()>

<CFSET val=StructInsert(Departments, "John", "Sales")>
<CFSET val=StructInsert(Departments, "Tom", "Finance")>
<CFSET val=StructInsert(Departments, "Mike", "Education")>

<!--- Build a table to display the contents --->

<CFOUTPUT>

<TABLE cellpadding="2" cellspacing="2">
    <TR>
    <TD><B>Employee</B></TD>
    <TD><B>Dept.</B></TD>
    </TR>

<!--- In CFLOOP, use ITEM to create a variable 
    called person to hold value of key as loop runs --->

<CFLOOP COLLECTION=#Departments# ITEM="person">

    <TR>
    <TD>#person#</TD>
    <TD>#Departments[person]#</TD>
    </TR>

</CFLOOP>

</TABLE>
</CFOUTPUT>


 
 
BackUp LevelNext
 
 

allaire     AllaireDoc@allaire.com
    Copyright © 1998, Allaire Corporation. All rights reserved.