note 87165 deleted from function.sort by danbrown

From: Date: Mon, 24 Nov 2008 16:55:08 +0000
Subject: note 87165 deleted from function.sort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146884@lists.php.net to get a copy of this message
Note Submitter: matt dot crinklaw at gmail dot com ---- jalil at measat dot org and Matthew Hood's methods of sorting arrays of objects are very very slow and should never be used. To sort objects, use PHP's native usort instead: <?php // common interface for all objects // that may be sorted interface Comparable { // return int < 0 if this object is less than $rhs // return 0 if this objects == $rhs // return int > 0 if this object > $rhs public function compareTo(&$rhs); } // test class class SomeClass implements Comparable { public $comparisonIndex; public function __construct($comparisonIndex) { $this->comparisonIndex = $comparisonIndex; } // the comparison logic for your class. // could be whatever public function compareTo(&$rhs) { return $this->comparisonIndex - $rhs->comparisonIndex; } } // the actual array definition and sorting: $myArray = array(new SomeClass(4), new SomeClass(2), new SomeClass(1), new SomeClass(11)); // sort $myArray using our defined comparison function 'compare' usort($myArray, 'compare'); // print out the results of our sort array_walk($myArray, 'walk'); // our comparison function // invoke compareTo on the passed in object function compare(&$lhs, &$rhs) { return $lhs->compareTo($rhs); } function walk(&$object, $key) { echo $object->comparisonIndex . ' '; } ?> Will print out: 1 2 4 11

« previous php.notes (#146884) next »