sorting a multidimension array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
psychotomus
Forum Contributor
Posts: 487
Joined: Fri Jul 11, 2003 1:59 am

sorting a multidimension array?

Post 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);
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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);
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
tecktalkcm0391
DevNet Resident
Posts: 1030
Joined: Fri May 26, 2006 9:25 am
Location: Florida

Post 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!?
Post Reply