Page 1 of 1

Array Sorting

Posted: Tue Jul 21, 2009 5:58 am
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.

Re: Array Sorting

Posted: Tue Jul 21, 2009 6:29 am
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().

Re: Array Sorting

Posted: Tue Jul 21, 2009 7:06 am
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