This section explains how to create and use structures in ColdFusion. The sample code in this section uses a structure called employee, which is used to add new employees to a corporate information system.
This section describes the following topics:
You can create a structure by creating a first key-pair or by using the ColdFusion StructNew
function.
You can create a structure by assigning a key-value pair. For example, the following line creates a structure named myStruct with one element, name, that has the value Macromedia.
<cfset myStruct.name="Macromedia">
Note: You can also create a structure using the structname
["keyname
"] format; for example, <cfset myStruct["name"] ="Macromedia">
.
You can create structures by assigning a variable name to the structure with the StructNew
function as follows:
<cfset mystructure
=StructNew()>
For example, to create a structure named departments, use the following syntax:
<cfset departments=StructNew()>
This creates an empty structure to which you can add data.
Use this technique to create structures if your application must run on ColdFusion server versions 5 and earlier.
You add an element to a structure by assigning the element a value or by using a ColdFusion function. It is cleaner and more efficient to use direct assignment, so only this technique is described.
You add structure key-value pairs by defining the value of the structure key, as shown in the following example:
<cfset myNewStructure.key1="A new structure with a new key"> <cfdump var=#myNewStructure#> <cfset myNewStructure.key2="Now I've added a second key"> <cfdump var=#myNewStructure#>
You can update structure element values by assignment or by using the StructUpdate
function. Direct assignment results in simpler code than using a function, so only the assignment technique is described.
To update a structure value, assign the key a new value. For example, the following code uses cfset
and object.property notation to create a new structure element called departments.John, and changes John's department from Sales to Marketing. It then uses associative array notation to change his department to Facilities. Each time the department changes, it displays the results:
<cfset departments=structnew()> <cfset departments.John = "Sales"> <cfoutput> Before the first change, John was in the #departments.John# Department<br> </cfoutput> <cfset Departments.John = "Marketing"> <cfoutput> After the first change, John is in the #departments.John# Department<br> </cfoutput> <cfset Departments["John"] = "Facilities"> <cfoutput> After the second change, John is in the #departments.John# Department<br> </cfoutput>