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.
Array Sorting
Moderator: General Moderators
- turbolemon
- Forum Commoner
- Posts: 70
- Joined: Tue Jul 14, 2009 6:45 am
- Location: Preston, UK
Re: Array Sorting
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:
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().
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
);
- turbolemon
- Forum Commoner
- Posts: 70
- Joined: Tue Jul 14, 2009 6:45 am
- Location: Preston, UK
Re: Array Sorting
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);
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