Skip to content

Instantly share code, notes, and snippets.

@nathanstanford2
Forked from erikvold/QueryToStruct.cfm
Created November 6, 2012 12:58
Show Gist options
  • Save nathanstanford2/4024574 to your computer and use it in GitHub Desktop.
Save nathanstanford2/4024574 to your computer and use it in GitHub Desktop.
CFML: QueryToStruct
<cffunction name="QueryToStruct" returntype="any" hint="Converts a query to a struct, or an array of structs">
<cfargument name="query" type="query" required="true"/>
<cfargument name="row" type="query"/>
<cfargument name="forceArray" type="boolean" default="false"/>
<cfscript>
var local = StructNew();
var result = StructNew();
var idx = "";
var colName = "";
var columnLabels = arguments.query.getMetaData().getColumnLabels();
</cfscript>
<cfif isDefined("arguments.row")>
<cfset local.row = arguments.row/>
<cfelseif arguments.query.recordCount eq 1>
<cfset local.row = 1/>
</cfif>
<cfif isDefined("local.row") and not arguments.forceArray>
<cfloop array="#columnLabels#" index="colName">
<cfset StructInsert(result, colName, arguments.query[colName][local.row])/>
</cfloop>
<cfelseif isDefined("local.row")>
<cfset result = ArrayNew(1)/>
<cfset ArrayAppend(result, StructNew())/>
<cfloop array="#columnLabels#" index="colName">
<cfset StructInsert(result[1], colName, arguments.query[colName][local.row])/>
</cfloop>
<cfelse>
<cfset result = ArrayNew(1)/>
<cfloop from="1" to="#arguments.query.recordCount#" index="idx">
<cfset local.tempStruct = StructNew()/>
<cfloop array="#columnLabels#" index="colName">
<cfset StructInsert(local.tempStruct, colName, arguments.query[colName][idx])/>
</cfloop>
<cfset ArrayAppend(result, local.tempStruct)/>
</cfloop>
</cfif>
<cfreturn result/>
</cffunction>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment