Sort an Associative Array of Structures

Here is a component that is based on my Macromedia Spectra days that takes an associative array of structures containing a common key and returns an array of key names from the associated array sorted by the common key.
 
Step 1: Create a component named structSortCommonSubKeys with the following code:
 
<cfcomponent hint="This CFC takes an associative array of structures containing a common key and returns an array of key names from the associative array sorted by the common key." output="false">
      <cffunction name="sortStruct" output="false" access="public" returntype="array" hint="Sort the array.">
            <cfargument name="struct" required="true" type="struct" />
            <cfargument name="commonSubKey" required="true" type="string" />
            <cfargument name="sortOrder" required="true" type="string" default="asc" />
            <cfargument name="sortType" required="false" type="string" default="textNoCase" />
     
            <!--- Struct may also be an array --->
            <cfif IsStruct(struct)>
                  <cfreturn StructSort(struct, sortType, sortOrder, commonSubKey) />
     
            <cfelseif IsArray(struct)>
                  <cfset struct = StructNew() />
                  <cfloop index="i" from="1" to="#ArrayLen(struct)#">
                        <cfset value = struct[i][commonSubKey] />
                       
                        <cfif NOT IsSimpleValue(value)>
                              <cfthrow
                              errorcode="0"
                              message="Sorting error."
                              detail="Array passed to CFC structSortCommonSubkeys cannot be sorted by a common subkey <b>#commonSubKey#</b> since the value of array['#keyName#']['#commonSubKey#'] is not a simple value."
                              />
                        </cfif>
                       
                        <cfset struct[i] = value />        
                  </cfloop>
                 
                  <cfreturn StructSort(struct, sortType, sortOrder, "") />
            </cfif>
      </cffunction>
</cfcomponent>
 
Step 2: Next, initialize the component using <cfobject> and sort an associative array using the sortStruct method.  In this example I am sorting by the startDate key in descending order.
 
<!--- Initialize CFC --->
<cfobject component="resource.components.structSortCommonSubKeys" name="sort" />
 
<!--- Sort associative structure --->
<cfset aEventsSorted = sort.sortStruct(stEvents,"startDate","DESC","")  />
 
Step 3: Then loop through the sorted associative array and output each key.
 
<cfoutput>
<cfloop from="1" to="#ArrayLen(aEventsSorted)#" index="x">
<p>#stEvents[aEventsSorted[x]].title#</p>
 
<p><a href="/#stEvents[aEventsSorted[x]].url#">#stEvents[aEventsSorted[x]].link#</a></p>
</cfloop>
</cfoutput>

0 Comments  |  ColdFusion  |  Send
Posted 10/7/08 @ 10:27 PM by Gerald Walsh
© 2000-2009 Lucem Solutions Mach-II