Ask Ben: Converting a Query to an Array

Posted July 10, 2006 at 8:50 AM

Tags: ColdFusion, Ask Ben

A new ColdFusion programmer emailed me recently asking:

How can I convert a ColdFusion query into an array?

When it comes to this type of conversion, there are a few things that you have to take into account. For starters, is it worth it? The ColdFusion query object is a very powerful, very flexible array-like object to begin with. It can already be accessed directly without having to loop over the record set. Is this conversion something you really need to do? Second, if you do want to make the conversion, what structure do you want? You can either mimic the existing query notation by creating a "Structure of Arrays" or you can do what I feel is a more natural feeling conversion to create an "Array of Structures".

To begin with, let's cover how you can access a query object as a structure. Once you see this, you might realize that no conversion is needed at all. The ColdFusion query object can be accessed directly like a structure of arrays:

 Launch code in new window » Download code as text file »

  • <cfset strValue = qRecords[ COLUMN_NAME ][ ROW_NUMBER ] />

The first index is the key value of the column you want to access, for example, "id" or "name". The second index value is the row for which you want to access that column. If you want to see that in english, think of it as "I want the value in the COLUMN_NAME column of the ROW_NUMBER row. After seeing this, you might not want to go through the processing overhead of converting the query object into any other structure as it is pretty awesome to start with.

After this, if you still want to convert the query object in to another structure, I suggest going to an array of structures. This adds memory overhead (over the structure of arrays method) since each row must have a copy of the column names (as look-up keys), but I think it is a much more natural way of thinking about the query set (especially if you are a traditional programmer).

In order to convert a query into an array, you basically have to create an array, loop over every row in the query record set, create a structure of the values in that row, and then append that structure to the array:

 Launch code in new window » Download code as text file »

  • <cffunction name="QueryToArray" access="public" returntype="array" output="false"
  • hint="This turns a query into an array of structures.">

  • <!--- Define arguments. --->
  • <cfargument name="Data" type="query" required="yes" />

  • <cfscript>

  • // Define the local scope.
  • var LOCAL = StructNew();

  • // Get the column names as an array.
  • LOCAL.Columns = ListToArray( ARGUMENTS.Data.ColumnList );

  • // Create an array that will hold the query equivalent.
  • LOCAL.QueryArray = ArrayNew( 1 );

  • // Loop over the query.
  • for (LOCAL.RowIndex = 1 ; LOCAL.RowIndex LTE ARGUMENTS.Data.RecordCount ; LOCAL.RowIndex = (LOCAL.RowIndex + 1)){

  • // Create a row structure.
  • LOCAL.Row = StructNew();

  • // Loop over the columns in this row.
  • for (LOCAL.ColumnIndex = 1 ; LOCAL.ColumnIndex LTE ArrayLen( LOCAL.Columns ) ; LOCAL.ColumnIndex = (LOCAL.ColumnIndex + 1)){

  • // Get a reference to the query column.
  • LOCAL.ColumnName = LOCAL.Columns[ LOCAL.ColumnIndex ];

  • // Store the query cell value into the struct by key.
  • LOCAL.Row[ LOCAL.ColumnName ] = ARGUMENTS.Data[ LOCAL.ColumnName ][ LOCAL.RowIndex ];

  • }

  • // Add the structure to the query array.
  • ArrayAppend( LOCAL.QueryArray, LOCAL.Row );

  • }

  • // Return the array equivalent.
  • return( LOCAL.QueryArray );

  • </cfscript>
  • </cffunction>

To test, let's set up a simple query using an ID column and a NAME column:

 Launch code in new window » Download code as text file »

  • <!--- Set up the query for testing. --->
  • <cfset qTest = QueryNew( "id, name" ) />

  • <cfset QueryAddRow( qTest ) />
  • <cfset qTest[ "id" ][ qTest.RecordCount ] = "1" />
  • <cfset qTest[ "name" ][ qTest.RecordCount ] = "molly" />

  • <cfset QueryAddRow( qTest ) />
  • <cfset qTest[ "id" ][ qTest.RecordCount ] = "2" />
  • <cfset qTest[ "name" ][ qTest.RecordCount ] = "Sophia" />

  • <cfset QueryAddRow( qTest ) />
  • <cfset qTest[ "id" ][ qTest.RecordCount ] = "3" />
  • <cfset qTest[ "name" ][ qTest.RecordCount ] = "Stefie" />

  • <cfset QueryAddRow( qTest ) />
  • <cfset qTest[ "id" ][ qTest.RecordCount ] = "4" />
  • <cfset qTest[ "name" ][ qTest.RecordCount ] = "Maud" />

Now, to convert that query to an array of structures, we simple call the QueryToArray() method and pass in the query as an argument.

 Launch code in new window » Download code as text file »

  • <!--- Convert the query to an array. --->
  • <cfset arrTest = QueryToArray( qTest ) />

Dumping out the array, you can clearly see that it is an array or structures. Each structure at each array index has keys correlating to the query column.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Aug 4, 2006 at 8:08 PM // reply »
8 Comments

Thank you for this.

"For starters, is it worth it?"
Yes, if you need to dynamically access the columns.
MyQuery[variables.col] unfortunately only works with Structs. :(


Dec 26, 2006 at 7:30 PM // reply »
2 Comments

Keeping up with 'Converting a Query to an Array' is tough nowadays...As part of the relaunch of their site, the folks at depressedpress.com (http://www.depressedpress.com) are presenting a series of CFML challenges. The first is converting a Query to an Array using only CFML as fast as you can. Merry Christmas of Poland!


Jan 12, 2007 at 6:23 AM // reply »
1 Comments

With regard to the comment:
MyQuery[variables.col] unfortunately only works with Structs. :(

Yes you can, but you need to suffix it with the row that you want, so it'd be MyQuery[variables.col][row]

If you're looping through the rows then just use the loop variable, or if you're inside a cfoutput or cfloop then just use currentRow.


Mar 1, 2007 at 10:40 PM // reply »
2 Comments

Nice solution, thank you.


Mar 1, 2007 at 10:41 PM // reply »
2 Comments

Nice solution, thank you.


Oct 30, 2007 at 4:43 PM // reply »
6 Comments

I was pulling my hair out trying to access a query column dynamically and saw this post. Thanks much for the tip!
It's funny how many years you can program CF and still find something new.


Dec 23, 2007 at 9:09 AM // reply »
1 Comments

THAT is exactly what i´m looking for! cool you are my daysaver, thank you very much for sharing its a great tutorial. merry xmas.


May 29, 2008 at 10:40 AM // reply »
4 Comments

Nice article. I used to count 1, 2, 3... but now I'm just counting 0, 1, 2... Thanks!


dcs
Jun 20, 2008 at 8:48 AM // reply »
10 Comments

Yes, if you need to dynamically access the columns.

Couldn't one also use the evaluate() function to dynamically access the columns? E.g.,

<cfset temp = evaluate("MyQuery.#variables.col#[#index#]")>

IIRC, inside a CFLOOP or CFOUTPUT of MyQuery one would only need to do the following:

<cfset temp = evaluate("#variables.col#")>

I actually prefer building queries (using queryNew(), queryAddRow(), etc.) to using arrays of structures or structures of arrays because queries are so powerful.


Jul 27, 2008 at 9:38 AM // reply »
1 Comments

Nice solution, thank you.


Jul 27, 2008 at 9:48 AM // reply »
1 Comments

Nice article. I used to count 1, 2, 3... but now I'm just counting 0, 1, 2... Thanks!


Aug 14, 2008 at 3:01 PM // reply »
1 Comments

Best answer I could find on the net on this topic. Thank you.


Aug 14, 2008 at 3:04 PM // reply »
6,515 Comments

@Mitran,

Awesome :)


Sep 8, 2009 at 10:33 AM // reply »
1 Comments

Thank you for this solution :-)


Oct 6, 2009 at 4:52 AM // reply »
1 Comments

thanks a LOT for this tutorial, it helped me ;)
searched quite a bit until i something usefull.


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 20, 2009 at 5:38 PM
Learning ColdFusion 8: CFImage Part I - Reading And Writing Images
Hi Ben, Great article. I've been looking around to see if ColdFusion image engine can programatically create the following "wrap around" effect: http://www.creativepro.com/article/photoshop-s-she ... read »
Nov 20, 2009 at 5:35 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Dave: I talked to Gert he suggested: <cfhttp method="get" url="http://{some cf website}" result="stuff" addtoken="yes" /> Note the addition of cfhttp attribute addtoken. That should persist y ... read »
Nov 20, 2009 at 5:23 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Todd, Ahh, gotcha, yeah that makes sense. ... read »
Nov 20, 2009 at 5:17 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
Ben, sorry if I didn't make this clear. You can make it work like that if you want, just put <cfset session.foo = 1> (and <cfset application.foo = 1>) in your OnRequestStart() and it reve ... read »
Nov 20, 2009 at 5:07 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Todd, I have seen tidbits about the way Railo handles session. I can understand that it lazy-loads sessions, but I also think that I might make some things more complicated. For example, often tim ... read »
Nov 20, 2009 at 4:53 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
Ben, you can ramp up the security by turning on J2EE session which gives you a third set of numbers other than CFID/CFTOKEN. There's a reason why ACF put this in place (other than just session replic ... read »
Nov 20, 2009 at 4:52 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
Case in point, Ben, you may not be aware of this, but in Railo - OnApplicationStart() & OnSessionStart() act differently than in ACF. ACF does: OnApplicationStart (1st hit) OnSessionStart (1st and e ... read »
Nov 20, 2009 at 4:46 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Todd, That's understandable. I am not sure if this really leaves any more security holes than the fact that using old cookie-based CFID / CFTOKEN values will create a new session using the old CFI ... read »