PHP - Sorting ArrayObject -


i'm having problem sorting items in php class extends arrayobject.

i creating classes, , way i've figured out add cmp() function put in same file, outside of class. can't seem put anyplace else because of way uasort requires function name string.

so i'm doing this:

class test extends arrayobject{      public function __construct(){         $this[] = array( 'test' => 'b' );         $this[] = array( 'test' => 'a' );         $this[] = array( 'test' => 'd' );         $this[] = array( 'test' => 'c' );     }       public function sort(){         $this->uasort('cmp');     }  }  function cmp($a, $b) {     if ($a['test'] == $b['test']) {         return 0;     } else {         return $a['test'] < $b['test'] ? -1 : 1;     } } 

which fine if i'm using 1 class this, if use 2 (either autoloading or require) breaks on trying invoke cmp() twice.

i guess point seems bad way this. there other way can keep cmp() function inside class itself?

you this, instead of calling function make anonymous function.

php 5.3.0 or higher only

class test extends arrayobject{      public function __construct(){         $this[] = array( 'test' => 'b' );         $this[] = array( 'test' => 'a' );         $this[] = array( 'test' => 'd' );         $this[] = array( 'test' => 'c' );     }       public function sort(){         $this->uasort(function($a, $b) {             if ($a['test'] == $b['test']) {                 return 0;             } else {                 return $a['test'] < $b['test'] ? -1 : 1;             }         });     } } 

as anonymous functions work on php 5.3.0 or higher, more compatible option if need target php versions below 5.3.0

below php 5.3.0

class test extends arrayobject{      public function __construct(){         $this[] = array( 'test' => 'b' );         $this[] = array( 'test' => 'a' );         $this[] = array( 'test' => 'd' );         $this[] = array( 'test' => 'c' );     }       public function sort(){         $this->uasort(array($this, 'cmp'));     }      public function cmp($a, $b) {         if ($a['test'] == $b['test']) {             return 0;         } else {             return $a['test'] < $b['test'] ? -1 : 1;         }     }  } 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -