RE: sortind arrays

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

 



On 25 January 2007 10:55, Alexander Sagen wrote:

> Roman Neuhauser skrev:
> > # kalles@xxxxxxxxxxxxx / 2007-01-25 08:12:14 +0200:
> > > How can I sort an array like this so that it would be ASC ordered
> > > by the [1] key in subarrays? I need to maintain only the subarray
> > > key - value pairs. (Do I make sense?) 
> > > 
> > > Array
> > > (
> > >     [0] => Array
> > >         (
> > >             [0] => Logo
> > >             [1] => NameC
> > >             [2] => Home
> > >             [3] => url
> > >         )
> > > 
> > >     [1] => Array
> > >         (
> > >             [0] => Logo
> > >             [1] => NameA
> > >             [2] => Home
> > >             [3] => url
> > >         )
> > > 
> > >     [2] => Array
> > >         (
> > >             [0] => Logo
> > >             [1] => NameG
> > >             [2] => Home
> > >             [3] => url
> > >         )
> > > }
> > 
> > http://www.php.net/usort
> > 
> I think usort would be a bit overkill, he would probably find himself
> making a function to sort and maintain the association between the
> subarrays. Go with array_multisort, it would be a one-liner.

What total tosh!  array_multisort() won't handle this one -- usort() is correct.  The only function needed is a (one-liner!) custom comparison to compare individual [1] elements -- usort() takes care of all the rest:

   function compare_1($a, $b) { return strcmp($a[1], $b[1]); }

   usort($array, 'compare_1');

Or even, for single use, collapse it to:

   usort($array, create_function('$a,$b', 'return strcmp($a[1], $b[1]);');

Cheers!

Mike

---------------------------------------------------------------------
Mike Ford,  Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Headingley Campus, LEEDS,  LS6 3QS,  United Kingdom
Email: m.ford@xxxxxxxxxxxxxx
Tel: +44 113 283 2600 extn 4730      Fax:  +44 113 283 3211 



To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux