Page 1 of 1

sorting a multidimension array?

Posted: Wed Aug 22, 2007 8:12 pm
by psychotomus
Strings are the strings i want associated with the perc's i want the results to be like this

String 3: 80%
String 1: 12%
String 2: 8%

how can I do this?


Code: Select all

$ar = array(
       array($strings[0], $strings[1], $strings[2], $strings[3], $strings[4], $strings[5], $strings[6], $strings[7]),
       array($percs[0],  $percs[1],  $percs[2],  $percs[3],  $percs[4],  $percs[5],  $percs[6],  $percs[7])
      );

array_multisort($ar[0], SORT_DESC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);

Posted: Wed Aug 22, 2007 8:33 pm
by VladSun
The input arrays are treated as columns of a table to be sorted by rows - this resembles the functionality of SQL ORDER BY clause. The first array is the primary one to sort by. The rows (values) in that array that compare the same are sorted by the next input array, and so on.

Code: Select all

$ar = array(
       array($strings[0], $strings[1], $strings[2], $strings[3], $strings[4], $strings[5], $strings[6], $strings[7]),
       array($percs[0],  $percs[1],  $percs[2],  $percs[3],  $percs[4],  $percs[5],  $percs[6],  $percs[7])
      );

array_multisort($ar[1], SORT_NUMERIC, SORT_DESC,
                $ar[0], SORT_DESC, SORT_STRING);

Posted: Wed Aug 22, 2007 8:33 pm
by tecktalkcm0391
forget the array_multisort and do something like this:

Code: Select all

foreach($ar[0] as $key => $string){
    print $string.": ".$ar[1][$key];
}
Edit: [s]sorry i thought i had it but i just lost it i'll repost if i remember :([/s]
I think the above will work now!?