How do I sort a 2 dimensional array?
ColdFusion does not provide a built-in way to sort a multi-dimensional array. However, there 2 ways to accomplish this task.
1) Turn the multi-dimensional array into a query and then use query of queries to sort it.
<cfset arr = arrayNew(2)>
<cfset arr[1][1] = "beta">
<cfset arr[2][1] = "bar">
<cfset arr[3][1] = "foo">
<cfset arr[4][1] = "alpha">
<cfset arr[1][2] = "car">
<cfset arr[2][2] = "boat">
<cfset arr[3][2] = "bike">
<cfset arr[4][2] = "car">
<!--- convert array to CF query --->
<cfscript>
myQuery = QueryNew("one,two");
for (i=1; i LTE ArrayLen(arr); i=i+1) {
newRow = QueryAddRow(myQuery);
QuerySetCell(myQuery, "one", #arr[i][1]# );
QuerySetCell(myQuery, "two", #arr[i][2]# );
}
</cfscript>
<cfdump var= #myQuery#>
<!--- Sort --->
<cfquery name="qSort"
dbtype = "query">
SELECT *
FROM myQuery
ORDER BY one
</cfquery>
<cfdump var= #qSort#>
2) You can sort single dimension arrays use the built in ColdFusion function arraySort(). So with this in mind, you can pull the array dimension you want to sort by into its own single dimension array and then use arraySort() on this single dimension array.
for (i=1; i LTE ArrayLen(arrayToSort); i=i+1) {
ArrayAppend(sortArray, arrayToSort[i][sortColumn]);
}
It is then a simple matter of reordering the rest of your multi-dimensional array based on the new sort order of the single dimension array.
ArraySort(sortArray, type, order);
for (i=1; i LTE ArrayLen(sortArray); i=i+1) {
thePosition = ListFind(theList, sortArray[i]);
theList = ListDeleteAt(theList, thePosition);
for (j=1; j LTE ArrayLen(arrayToSort[thePosition]); j=j+1) {
arrayToReturn[counter][j] = arrayToSort[thePosition][j];
}
ArrayDeleteAt(arrayToSort, thePosition);
counter = counter + 1;
}
The above code was taken from Robert West's ArraySort2D() function that can be found at: http://www.cflib.org/udf.cfm?ID=390
This question was written by Jeremy Petersen.
It was last updated on May 8, 2006 at 5:24:26 PM EDT.
CFML Referenced
<cfquery>
<cfscript>
ArraySort()
Categories
Comments
Comment made by Ryan Guill on May 8, 2006 at 3:38 PM
Note that you can also turn the array into a query and then use query of queries to sort it. This can be useful when sorting the same data over and over.
Comment made by Jeremy Petersen on May 8, 2006 at 5:25 PM
Added a quick sample showing query of queries
Comment made by samon on May 17, 2006 at 11:08 PM
you also can do it like this:
QueryAddColumn(myQuery, "one", "Varchar", arr[1]);
if you do it like this ,i think the capability is best,or user structSort()
Comment made by Sam Maitz on November 10, 2008 at 4:00 PM
The first option of the sort a 2 dimensional array worked great in CF5. But... is there a way to change or eliminate the Red borders and shadding?