[thelist] Sorting 2D array in PHP

kerkness phparch at gmail.com
Fri Mar 18 10:58:28 CST 2005


On Fri, 18 Mar 2005 15:35:53 +0200, Juha Suni <juha.suni at ilmiantajat.fi> wrote:
> Brooking, John wrote:
> > 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.
> 
> Yes it does, usort(). See:
> http://www.php.net/usort

How can I use usort() so that my comparison function can be a method
of the class file? I would like to do something like this...

class fruityClass {
  var $fruit = array();
  function getFruit(){
       usort($this->fruit, "cmpFruit");
       return $this->fruit;
  }
  function cmpFruit($a,$b){
   if ($a['name'] == $b['name']) {
       return 0;
   }
     return ($a['name'] < $b['name']) ? -1 : 1;
  }  
}

This example doesn't work, in fact I can't even get an error message
out of it. I've had to move cmpFruit out side of the class and declare
it as a normal function. Which to me seems like a sloppy approach.
Anyone have a better idea?


More information about the thelist mailing list