Chapter 9: Handling Complex Data with Structures
<CFOUTPUT><HR>Employee Add Complete</CFOUTPUT>
</CFCASE>
</CFSWITCH>
Using Structures as Associative Arrays
You can also use structures as associative arrays. When used as associative arrays,
structures index repetitive 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,
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>Department</B></TD>
</TR>
<!--- In CFLOOP, use ITEM to create a variable
)
</CFOUTPUT>
</CFQUERY>
</CFIF>
Departments["John"]
.
119