Skip to main content
Inspiring
November 5, 2018
Answered

Sort / CFLOOP

  • November 5, 2018
  • 1 reply
  • 2536 views

I have an excel that I read and create a query object using this code

<cfspreadsheet action="read" src="#theFile#" query="qData" headerrow="1" excludeHeaderRow ="true"  columns="9,15,51,56,57,58,59"   />

So now I have a query object that I output and it outputs in the order that is in the excel.

I loop through it like this

<cfloop query="qData">

and I get this

IDValue
1Adams
2Jones
3Smith
4Johnson
5Williams

Now I need to do the order in reverse like this

IDValues
5Williams
4Johnson
3Smith
2Jones
1Adams

  Can I sort by a loop? How ?

This topic has been closed for replies.
Correct answer WolfShade

This option should work?


  1. <cfoutput> 
  2. <cfloop from="#qData.recordcount#" to="1" step="-1" index="idx"
  3.     #qData.ID[idx]#        #qData.Values[idx]#<br /> 
  4. </cfloop> 
  5. </cfoutput> 

Yup.  Basically, you are going through the query backwards, starting at the last record, moving "step -1" (backwards) to the first record.  The "idx" is the index based upon where in the iterative loop you are, and the bracket notation is getting the data from that index of the query object.

HTH,

^ _ ^

1 reply

WolfShade
Legend
November 5, 2018

There are a couple of ways to sort the query object, I believe.

One way would be to loop the object in reverse, if you are strictly going for a reverse-only output.

<cfoutput>

<cfloop from="#qData.recordcount#" to="1" step="-1" index="idx">

    #qData.ID[idx]#        #qData.Values[idx]#<br />

</cfloop>

</cfoutput>

If the IDs are always sequential, you can reverse sort like so:

<cfset qDdata.sort(qDdata.findColumn("ID"), FALSE)>

Then output as you normally would.  The "FALSE" means DESCENDING; "TRUE" would be ASCENDING.

HTH,

^ _ ^

weezerboyAuthor
Inspiring
November 5, 2018

Sorry, Wolf. I had some bad info and didn't phrase the question correctly

This is the query object . When it loops the first time it outputs like this

    

TITLECITYFIRST_NAMELAST_NAME
Mr.DetroitSteveSmith
Ms.VA BeachRonMoore
Mr.MadisonPeterSimpkins
Mr.ClevelandJohn

Warner

There is NO ID column

Is there a way to sort these via cfloop so that it goes Warner, Simpkins, Moore Smith?

WolfShade
Legend
November 5, 2018

No, because that's not alphabetical or reverse-alphabetical.  Is there ANY kind of sequential ID being provided?

If you wanted it sorted alphabetically or reverse-alphabetically, then the Java sort that I suggested could be used on LAST_NAME, or FIRST_NAME, or CITY.

If there are no IDs, then the first option I suggested should work, if you are truly sorting reverse of the information as it was constructed.

V/r,

^ _ ^