Re: Question about usort

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

 



Dean Householder wrote:
> 
> 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
...

> 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.

Well, you can't pass any more vars through usort, but you could use a 
global variable (ick) ooooorr..you could do some really sticky stuff 
with create_function, which I wouldn't recommend, since it doesn't do 
much for readability, but consider the following:

<?php
function sortit($key, $direction=0){
    return create_function('$a,$b', '
       if($a["'.$key.'"] == $b["'.$key.'"]){
          return 0;
       }
       if($a["'.$key.'"] '.($direction ? '>' : '<').' $b["'.$key.'"]){
          return -1;
       }else{
          return 1;
       }
    ');
}
 

$arr= array(
    array(
       'name' => 'bill',
       'age' => 20
    ),
    array(
       'name' => 'abe',
       'age' => 19
    )
);
 

print_r($arr);
uasort($arr, sortit('name'));
print_r($arr);
uasort($arr, sortit('name', 1));
print_r($arr);
?>

That COULD do what you're looking for.

-- 
regards,

Nezar Nielsen
http://fez.dk



------------------------ Yahoo! Groups Sponsor --------------------~--> 
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/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