I recently came across a problem when trying to output a structure using a loop. Although I had ordered my SQL and my input into the structure, the output was in a completely different order. This is due to the hash mapping that structures use, and although it proves well for performance it suffers in ordering the output of your data. First, I created my structure and then looped through my query and incremented the counts in my list, based on the position:
<cfset objCustomers = StructNew()>
<cfloop query="customerQry">
<cfset cntList = "0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0">
<cfif custName NEQ "">
<cfset strCustomer = "#custName#">
<cfset custExists = StructFindKey(objCustomers, "#custName#")>
<cfif ArrayIsEmpty(custExists)>
<cfif customerQry.custStatusID EQ 1 AND customerQry.custProgramID EQ 8>
<cfset badCustomers = listGetAt(cntList, 2, "|")>
<cfset badCustomers = badCustomers + 1>
<cfset cntList = listSetAt(cntLIst, 2, badCustomers , "|")>
</cfif>
<cfset totalCustomers = listGetAt(cntList, 1, "|")>
<cfset totalCustomers = totalCustomers + 1>
<cfset countsList = listSetAt(countsList, 1, totalStudents, "|")>
<cfset objUniversities[strUniversity] = "#countsList#">
<cfelse>
<cfset cntList = objUniversities[strUniversity]>
<cfset totalCustomers = listGetAt(cntList, 1, "|")>
<cfset totalCustomers = totalCustomers + 1>
<cfset countsList = listSetAt(cntList, 1, totalCustomers , "|")>
<cfscript>
StructUpdate(objCustomers, "#custName#", cntList);
</cfscript>
</cfif>
</cfloop>
So, now that we have our structure built how do we output the data so it orders by customer name? If you loop through the structure, you cant; it will output in a very different order. What you first have to do is manually create a query and load this structure data into it:
<cfset custCountQry = queryNew("custName,totalCustomers, badCustomers")>
<cfloop collection="#objCustomers#" item="customer">
<cfoutput>
<cfset custCounts = "#StructFind(objCustomers, customer)#">
<cfset totalCustomers = listGetAt(custCounts, 1, "|")>
<cfset badCustomers = listGetAt(custCounts, 2, "|")>
<cfset queryAddRow(custCountQry)>
<cfset querySetCell(custCountQry,"totalCustomers", "#totalCustomers#")>
<cfset querySetCell(custCountQry,"badCustomers", "#badCustomers#")>
</cfoutput>
Now, you will have a query you can perform SQL on and order your results:
<cfquery name="getCustomerSummary" dbtype="query">
SELECT *
FROM custCountQry
ORDER BY [custName] ASC
</cfquery>
You can now use a cfoutput query to return your results in order!