RE: [PHP] sorting multi-dimensional array
| From: | Ford, Mike [LSS] | Date: | Thu, 20 Feb 2003 14:35:09 +0000 |
| Subject: | RE: [PHP] sorting multi-dimensional array | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-136361@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Steve Buehler [mailto:steve@vespro.com]
> Sent: 20 February 2003 05:25
>
> Ahhh....finally did it with usort. Thanks to those who gave me that
> answer. Now here is a question for that. I would like to
> re-use my "cmp"
> function without having to rewrite it each time. Can it be
> written so that
> instead of "divname" being hard coded, that I can pass the
> sort field in
> the usort call. That way, I can either sort by "divname" and
> do another
> sort by "divid" for seperate results without having to have
> multiple "cmp"
> type functions. I hope that made since. Lack of sleep isn't
> good when
> programming. Below is my sorting code.
>
>
> function cmp ($a, $b) {
> return strcmp($a["divname"], $b["divname"]);
> }
>
> usort($array, "cmp");
Well, the only obvious way I can think of is to use a global variable to set the array index you
want to sort by -- something like:
function cmp ($a, $b) {
global $field;
return strcmp($a[$field], $b[$field]);
}
$field = "divname";
usort($array, "cmp");
$field = "divid";
usort($array, "cmp");
I haven't tested this, but I think it should work...!
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@lmu.ac.uk
Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211