View Single Post
  #52 (permalink)  
Old 02-21-2008, 02:02 AM
prasannavigneshr prasannavigneshr is offline
D-Web Incredible
 
Join Date: Feb 2007
Posts: 1,321
prasannavigneshr is on a distinguished road
Send a message via MSN to prasannavigneshr
Thumbs up ColdFusion Tips & Tricks - Sorting an Array by the 2nd demension

Sorting an Array by the 2nd dimension


If you wish to sort by the 2nd demension, specify the first deminsion in with the array in the ArraySort. Here is the example from the CF 4.5 ArraySort example, modifed to sort via the 2nd deminsion:

Code:
<CFSET myAlphaArray = ArraySort(myArray[2], "textnocase", "desc")>
Note that setting "myAlphaArray" is missleading in having you think that it creates a new array called "myAlphaArray". This is not the case. The variable will contain a "Yes" if the sort was successfull.

In the attached code below, I create an array with 3 rows and 26 cells in each row. I sort only the 2nd row by alpha descending. Rows 1 and 3 remain in the orignial sort order. When the program executes, you'll see two tables like the following:

q w e r t y u i o p l k j h g f d s a z x c v b n m
q w e r t y u i o p l k j h g f d s a z x c v b n m
q w e r t y u i o p l k j h g f d s a z x c v b n m

q w e r t y u i o p l k j h g f d s a z x c v b n m
z y x w v u t s r q p o n m l k j i h g f e d c b a
q w e r t y u i o p l k j h g f d s a z x c v b n m


Example HTML/CFML code:
Code:
<CFSET list="q,w,e,r,t,y,u,i,o,p,l,k,j,h,g,f,d,s,a,z,x,c,v,b,n,m">
<CFSET myarray=ArrayNew(2)>
<CFLOOP index="x" from="1" to="3">
  <CFLOOP index="y" from="1" to="26">
    <CFSET myarray[x][y]=ListGetAt(list,y)>
  </CFLOOP>
</CFLOOP>

<table border="1">
  <CFLOOP index="x" from="1" to="3">
    <tr>
      <cfloop index="y" from="1" to="26">
        <CFOUTPUT><td>#myarray[x][y]#</td></CFOUTPUT>
      </CFLOOP>
    </tr>
  </CFLOOP>
</table>
<br><br>

<CFSET tmp=ArraySort(myarray[2],"textnocase", "desc")>

<table border="1">
  <CFLOOP index="x" from="1" to="#ArrayLen(myarray)#">
    <tr>
      <cfloop index="y" from="1" to="26">
        <CFOUTPUT><td>#myarray[x][y]#</td></CFOUTPUT>
      </CFLOOP>
    </tr>
  </CFLOOP>
</table>
__________________
Prasanna Vignesh
MCPD | Web Developer
Reply With Quote