Forum Moderators: coopster

Message Too Old, No Replies

Array Sort

Sort on multiple arrays on last field in array

         

brynt72

6:15 am on Aug 26, 2003 (gmt 0)

10+ Year Member



How can I sort on arrays similar to the following...

$ar1=array(10,3,4,6,56)
$ar2=array(10,3,4,6,23)
$ar3=array(10,3,4,6,45)
$ar4=array(10,3,4,6,34)
$ar5=array(10,3,4,3,15)

I would like to be able to sort on the last field and spit them out as follows

$ar5=array(10,3,4,3,15)
$ar2=array(10,3,4,6,23)
$ar4=array(10,3,4,6,34)
$ar3=array(10,3,4,6,45)
$ar1=array(10,3,4,6,56)

RonPK

6:41 am on Aug 26, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think you'll need to put your arrays into another one and use array_multisort, like this:

$allArrs = array(ar1 => $ar1, ar2 => $ar2, ar3 => $ar3, ar4 => $ar4, ar5 => $ar5);
array_multisort($allArrs, SORT_ASC);

Use print_r($allArrs); to see what happens.

brynt72

6:47 am on Aug 26, 2003 (gmt 0)

10+ Year Member



Can you define by what field it is sorted on?

I would like to sort by the last field or also by the 2nd or 3rd. It may depend.

Thanks

RonPK

7:08 am on Aug 26, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



In that case, use uasort() and a user defined comparison function.

function cmp ($a, $b) {
return strcmp($a[3], $b[3]);
}
uasort($allArrs, "cmp");

In this case '3' is the index you're using to sort on.

brynt72

7:26 am on Aug 26, 2003 (gmt 0)

10+ Year Member



Thank you
that seems to work like I need it to.