Array Sorting

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
gth759k
Forum Commoner
Posts: 76
Joined: Mon Jun 15, 2009 3:04 am

Array Sorting

Post by gth759k »

This might be simpler than I'm making it, but I still need help. I have an array with corresponding names and values.

For example:
$scoresbefore = array("Bob", 9, "Karen", 3, "James", 12, "Pete", 6, "Kelly", 7);
$scoresafter = array("Karen", 3,"Pete", 6,"Kelly", 7,"Bob", 9,"James", 12);

What I'm trying to do is sort by the values and retain the corresponding name in front of it. Maybe there is a better way of doing this. If you know of one please tell me. Any help would be appreciated. Thanks.
User avatar
turbolemon
Forum Commoner
Posts: 70
Joined: Tue Jul 14, 2009 6:45 am
Location: Preston, UK

Re: Array Sorting

Post by turbolemon »

If you wish to sort an array but retain the indexes, you can use the asort function http://www.php.net/manual/en/function.asort.php. Then you can just store the result of array_keys http://uk3.php.net/array_keys/ before and after to get the ordering.

Are you trying to create a associative array with the name as the index and numeric value? If so, you need to use the following syntax:

Code: Select all

 
$scores = array(
 "Bob" => 9,
 "Karen" => 3,
 "James" => 12,
 "Pete" => 6,
 "Kelly" => 7
);
 
Then if you want to sort it, use asort($scores,SORT_NUMERIC); to order by ascending score (descending would use arsort()). You can sort by key using ksort() and krsort().
User avatar
turbolemon
Forum Commoner
Posts: 70
Joined: Tue Jul 14, 2009 6:45 am
Location: Preston, UK

Re: Array Sorting

Post by turbolemon »

Code: Select all

 
$array = array(
  '0450943907'  => 9,
  '7890320432'  => 3,
  '692039845'   => 12,
  '6468244129'  => 6,
  '1335343101'  => 7
 );
 
$before = array_keys ($array);
 
var_dump($array);
 
asort($array,SORT_NUMERIC);
 
var_dump($array);
 
On my server, outputs

Code: Select all

 
array
  '0450943907' => int 9
  '7890320432' => int 3
  692039845 => int 12
  '6468244129' => int 6
  1335343101 => int 7
 
array
  '7890320432' => int 3
  '6468244129' => int 6
  1335343101 => int 7
  '0450943907' => int 9
  692039845 => int 12
 
Post Reply