[thelist] Sorting 2D array in PHP

Brooking, John John.Brooking at sappi.com
Fri Mar 18 05:48:00 CST 2005


I'm finally taking the plunge and learning PHP. I'm currently trying to figure out the easiest way to sort a database-type 2D array, such as:

   $fruit = array( array( "name" => "pear"  
                        , "color" => "green" 
                        , "texture" => "squishy" 
                        )
                 , array( "name" => "apple" 
                        , "color" => "red"   
                        , "texture" => "crunchy" 
                        ), 
                 , array( "name" => "banana"
                        , "color" => "yellow"   
                        , "texture" => "firm" 
                        ),
                 );
                 
I've been looking at the PHP array functions, and the closest I find is array_multisort, but that seems to require that you transpose your arrow to be sets of columns rather than sets of rows, and that seems very counter-intuitive and inconvenient. What I want is something where I can pass the $fruit array, and say sort each sub-array by a list of their keys, something like: mySort( $fruit, array( "name", "-color" )). (I'm proposing that a leading "-" would mean descending.) I would want this to re-order the outer array integer keys so that $fruit[0] is the apple array, $fruit[1] is the banana array, and $fruit[2] is the pear array.

Barring that, if I were in Perl, I would just call the Perl sort function and pass my own comparison function pointer. Does PHP have such a mechanism? I haven't found it, if it does.

Any ideas would be appreciated.

- John

This message may contain information which is private, privileged or confidential and is intended solely for the use of the individual or entity named in the message. If you are not the intended recipient of this message, please notify the sender thereof and destroy / delete the message. Neither the sender nor Sappi Limited (including its subsidiaries and associated companies) shall incur any liability resulting directly or indirectly from accessing any of the attached files which may contain a virus or the like.



More information about the thelist mailing list