문제

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?

도움이 되었습니까?

해결책

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>

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top