note 87165 added to function.sort

From: Date: Sat, 22 Nov 2008 03:01:28 +0000
Subject: note 87165 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-146822@lists.php.net to get a copy of this message
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 ---- Server IP: 194.153.94.10 Probable Submitter: 98.204.103.230 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/87165 Del: integrated -- https://master.php.net/note/delete/87165/integrated Del: useless -- https://master.php.net/note/delete/87165/useless Del: bad code -- https://master.php.net/note/delete/87165/bad+code Del: spam -- https://master.php.net/note/delete/87165/spam Del: non-english -- https://master.php.net/note/delete/87165/non-english Del: in docs -- https://master.php.net/note/delete/87165/in+docs Del: other reasons-- https://master.php.net/note/delete/87165 Reject -- https://master.php.net/note/reject/87165 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#146822) next »