View comments | RSS feed

Populating an array from a query

When populating an array from a query, keep the following things in mind:

You can use a cfset tag with the following syntax to define values for array indexes:

<cfset arrayName[index]=queryColumn[row]>

In the following example, a cfloop tag places four columns of data from a sample data source into an array, myarray.

<!--- Do the query --->
<cfquery name="test" datasource="cfdocexamples">
   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>
   <cfset myarray[CurrentRow][2]=LastName>
   <cfset myarray[CurrentRow][3]=FirstName>
   <cfset myarray[CurrentRow][4]=Email>
</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>

This example uses the query object built-in variable CurrentRow to index the first dimension of the array.


ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | KnowledgeBase | Bug Reporting

Version 7

Comments


hpottash said on Apr 4, 2006 at 7:36 AM :
rather than writing loops for a one dementional array you can also use the following trick:
<cfset myarray = listToArray(valueList(test.FirstName))>
Not as messy, though I don't know how it compairs for speed.

(it's also worth pointing out that if you susspect you have comma's in your data you might want to try doing it with a diffrent delimiter such as:
<cfset myarray = listToArray(valueList(test.FirstName,"|"),"|")> )
gnerase said on Jun 15, 2006 at 4:40 PM :
Just to correct the statement: <cfset total_records=test.recordcount>. There should be "#" signs. It should read: <cfset total_records=#test.recordcount#>.
HorsePunchKid said on Mar 7, 2007 at 1:13 PM :
gnerase: No, the given code is correct and preferable. The pound signs you suggest are superfluous. As a rule of thumb, the only places you need pound signs are inside <cfoutput> blocks and inside strings (e.g. <cfset Foo="Bar#N#Baz">). Adobe has some best practices documented here:

http://livedocs.adobe.com/coldfusion/7/htmldocs/00000932.htm

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/coldfusion/7/htmldocs/00000957.htm