Jump to content

sorting array descending/ascending order confusion


silverglade

Recommended Posts

hi, im confused with this code , i thought that "Grisold" should come first in the output list, and "Champy" should come last since the sort is ascending. because "gary" comes last in the first sort. any help greatly appreciate to enlighten me .

 

<?php

   $staff["givenname"][0] = "Jason";
   $staff["givenname"][1] = "Manny";
   $staff["givenname"][2] = "Gary";
   $staff["givenname"][3] = "James";
   $staff["surname"][0] = "Gilmore";
   $staff["surname"][1] = "Champy";
   $staff["surname"][2] = "Grisold";
   $staff["surname"][3] = "Gilmore";

   $res = array_multisort($staff["surname"],SORT_STRING,SORT_ASC,
                          $staff["givenname"],SORT_STRING,SORT_ASC);

   print_r($staff);
  
?>

 

 

output is as follows:

Array ( [givenname] => Array ( [0] => Manny [1] => James [2] => Jason [3] => Gary ) [surname] => Array ( [0] => Champy [1] => Gilmore [2] => Gilmore [3] => Grisold ) ) 

Your code is sorting by 'surname' first and then by 'givenname'. So, it will be sorted by lastname, firstname is ascending order: a comes before b, b before c, etc. Your results should be:

 

- Champy, Many

- Gilmore, James

- Gilmore, Jason

- Grisold, Gary

nevermind i DO get it now lol. ok so it sorts the last names first, then if it hits duplicate last names it sorts the first names? i thought it was sorting both first names and last names and that the first and last names were unrelated. but i still dont get how the first and last names are related because they are in two different arrays arent they?

Yes, but the function will relate them by the index when you use it in this manner. By doing a multisort on the two arrays the function is associating $staff["givenname"][0] with $staff["surname"][0].

 

Read the manual for this function. Specifically look at examples #1 and #2

 

http://us3.php.net/manual/en/function.array-multisort.php

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.