Question about usort

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




I have a multi-dimensional array -- an array of associative arrays --
that I would like to sort in a number of non-trivial ways (i.e., sort,
asort, ksort are not sufficient).  I'm trying to figure out how to do
this using usort without creating a dozen different functions.  The
array has as structure similar to the following:
 
Array
(
    [0] => Array
        (
            [name] => Alice
            [title] => Teacher
            [num] => 10
        )
 
    [1] => Array
        (
            [name] => Ben
            [title] => Programmer
            [num] => 20
        )
 
    [2] => Array
        (
            [name] => Carl
            [title] => Executive
            [num] => 30
        )
 
)

Currently I have to create three different functions to sort on each
of the three fileds (name, title, num) like so:
 
function sort_by_name ($a, $b) {
  return strcasecmp($a['name'], $b['name']);
}
function sort_by_title ($a, $b) {
  return strcasecmp($a['title'], $b['title']);
}
function sort_by_name ($a, $b) {
  return ($a['num'] < $b['num']);
}

Then I call it in an if statement:
 
if($_GET['sort'] == 'name') {
  sort($array, "sort_by_name");
} elseif($_GET['sort'] == 'title') {
  sort($array, "sort_by_title");
} elseif($_GET['sort'] == 'num') {
  sort($array, "sort_by_num");
}
 
Of course, if I want to do reverse sorting, I have to create three
more functions and three more if statements.  Does anyone have a
suggestion on how I could pass data through usort to the callback
function, such as a flag indicating reverse (or not), and a variable
indicating the field name to sort on?  Then this could all be done
with one function.
 
Thanks!
 Dean





------------------------ Yahoo! Groups Sponsor --------------------~--> 
$9.95 domain names from Yahoo!. Register anything.
http://us.click.yahoo.com/J8kdrA/y20IAA/yQLSAA/saFolB/TM
--------------------------------------------------------------------~-> 

PHP Data object relational mapping generator - http://www.meta-language.net/ 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/php-objects/

<*> To unsubscribe from this group, send an email to:
    php-objects-unsubscribe@yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 




[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Soap]     [Kernel Newbies]     [Yosemite]     [Yosemite Campsites]

  Powered by Linux