User Guide
Populating Arrays with Data 123
Populating an array from a query
When populating an array from a query, keep the following things in mind:
• Query data cannot be added to an array all at once. A looping structure is
generally required to populate an array from a query.
• Query column data can be referenced using array-like syntax. For example,
myquery.col_name[1] references data in the first row in the column col_name of
the myquery query.
• Inside a
cfloop query= loop, you do not have to specify the query name to
reference the query’s variables.
You can use a cfset tag to define values for array indexes, as in the following
example:
<cfset arrayname[x]=column[row]>
In the following example, a cfloop places four columns of data from a sample data
source into an array, "myarray."
<!--- Do the query --->
<cfquery name="test" datasource="cfsnippets">
SELECT Emp_ID, LastName, FirstName, Email
FROM Employees
</cfquery>
<!--- Declare the array --->
<cfset myarray=arraynew(2)>
<!--- Populate the array row by row --->
<cfloop query="test">
<cfset myarray[currentrow][1]=Emp_ID[currentrow]>
<cfset myarray[currentrow][2]=LastName[currentrow]>
<cfset myarray[currentrow][3]=FirstName[currentrow]>
<cfset myarray[currentrow][4]=Email[currentrow]>
</cfloop>
<!--- Now, create a loop to output the array contents --->
<cfset total_records=test.recordcount>
<cfloop index="Counter" from=1 to="#Total_Records#">
<cfoutput>
ID: #MyArray[Counter][1]#,
LASTNAME: #MyArray[Counter][2]#,
FIRSTNAME: #MyArray[Counter][3]#,
EMAIL: #MyArray[Counter][4]# <br>
</cfoutput>
</cfloop>