Reputation: 63
Hi I have a loop which outputs
<cfloop collection="#SESSION.squad.achievements#" item="key">
The problem is the key(which is a year) is output in the wrong order, it outputs
2009
2010
2011
As far as I can see there in no built in method for changing the order or am I missing something?
Upvotes: 6
Views: 7217
Reputation: 1772
Instead of this:
<cfset SESSION.squad.achievements = StructNew() />
Use this:
<cfset SESSION.squad.achievements = createObject("java", "java.util.LinkedHashMap").init() />
This will maintain the order.
Source: http://www.aftergeek.com/2010/03/preserving-structure-sort-order-in.html
Upvotes: 2
Reputation: 31912
Coldfusion structures don't have an order, so you can't guarantee when looping over a struct that the keys will come out in the same order they were inserted (or numerically/alphabetically/etc).
If the order is important, use an array instead.
An alternative would be to get all the keys in an array, then order that array, and loop over it, but inside the loop referencing the structure.
<!--- get an array of the keys in the desired order --->
<cfset achievements = StructSort(SESSION.squad.achievements, "numeric", "desc")>
<!--- loop over that array --->
<cfloop index="year" array="#achievements#">
<!--- refer back to the struct, keyed on the current year we're looping on --->
#year# : #SESSION.squad.achievements[year]#
</cfloop>
Upvotes: 10