Re: Sorting Multidimensional Associative arrays
| From: | Carroll Barrett | Date: | Mon, 26 Jun 2000 22:52:20 +0000 |
| Subject: | Re: Sorting Multidimensional Associative arrays | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-3229@lists.php.net to get a copy of this message | ||
Alex,
If you make $r into an array of arrays, then you can use usort()
as follows. I did not try usort() with the 2-dimensional array
you were using.
$r=array(array("skill"=>"supervising","age"=>44,"experience"=>23)
,
array("skill"=>"welding","age"=>30,"experience"=>9),
array("skill"=>"carpentry","age"=>60,"experience"=>39),
array("skill"=>"painting","age"=>57,"experience"=>36));
function compare($a,$b) {
if ($a["age"]==$b["age"])
return 0;
return ($a["age"] > $b["age"]) ? -1 : 1;
}
usort($r,compare);
for($i=0;$i<count($r);$i++) {
$a=$r[$i];
echo "Skill=${a["skill"]} Age=${a["age"]}
Experience=${a["experience"]}<BR
>";
}
which produces:
Skill=carpentry Age=60 Experience=39
Skill=painting Age=57 Experience=36
Skill=supervising Age=44 Experience=23
Skill=welding Age=30 Experience=9
Regards,
Carroll Barrett
-----Original Message-----
From: Alex V. <alex@quad.com.ar>
To: php-general@lists.php.net <php-general@lists.php.net>
Date: Monday, June 26, 2000 5:29 PM
Subject: [PHP-GENERAL] Sorting Multidimensional Associative
arrays
>I'm trying to sort a multidimensional asociative array.
>
>The array looks like this:
>
>$r[$user]['skill']
>$r[$user]['age']
>$r[$user]['experience']
>
>is it possible to sort this array in such way that the first key
of it
>(user) is the user with the highest age number and the last user
is the one
>with lowest age number? That is.. an descending sorting of users
by their
>age.
>
etc.