The problem is that the key (...">

Orders with cfloop

Hi, I have a loop that outputs

<cfloop collection="#SESSION.squad.achievements#" item="key"> 

The problem is that the key (which is the year) is displayed in the wrong order, it outputs

2009

2010

2011

As far as I can see, there is no built-in method for changing the order or am I missing something?

+6
source share
2 answers

Coldfusion structures have no order, so you cannot guarantee that when you go through the structure, the keys will come out in the same order as they were inserted (either in numerical / alphabetical order / etc).

If order is important, use an array instead.

An alternative would be to get all the keys in the array, then arrange this array and loop over it, but inside the loop that refers to 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> 
+10
source

Instead of this:

 <cfset SESSION.squad.achievements = StructNew() /> 

Use this:

 <cfset SESSION.squad.achievements = createObject("java", "java.util.LinkedHashMap").init() /> 

This will maintain order.

Source: http://www.aftergeek.com/2010/03/preserving-structure-sort-order-in.html

+1
source

Source: https://habr.com/ru/post/887179/


All Articles