Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ordering with cfloop

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?

like image 914
Ross Mark Avatar asked May 03 '11 09:05

Ross Mark


2 Answers

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>
like image 101
duncan Avatar answered Nov 26 '22 01:11

duncan


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

like image 45
Deepak Yadav Avatar answered Nov 26 '22 02:11

Deepak Yadav