note 109329 added to function.usort
| From: | JianWu | Date: | Fri, 06 Jul 2012 21:16:22 +0000 |
| Subject: | note 109329 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-189056@lists.php.net to get a copy of this message | ||
The usort function actually moves $b up when the callback function returns both 0 and 1. If you
want to preserve the original order in the array, return 1 when $a == $b instead of 0. Try this
code below to see how usort alters the order of the original array when all values are the same.
<?php
class TestObj {
private $name;
private $id;
function TestObj($name, $id) {
$this->name = $name;
$this->id = $id;
}
static function cmp_obj($a, $b) {
$al = strtolower($a->name);
$bl = strtolower($b->name);
if ($al == $bl) {
return 0; // return 1 if you don't want $b to go in front of $a
}
return ($al > $bl) ? +1 : -1;
}
}
$a[] = new TestObj("a", 1);
$a[] = new TestObj("a", 2);
$a[] = new TestObj("a", 3);
var_dump($a);
usort($a, array("TestObj", "cmp_obj"));
var_dump($a);
----
Server IP: 64.71.164.2
Probable Submitter: 198.183.141.65
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/109329
Del: integrated -- https://master.php.net/note/delete/109329/integrated
Del: useless -- https://master.php.net/note/delete/109329/useless
Del: bad code -- https://master.php.net/note/delete/109329/bad+code
Del: spam -- https://master.php.net/note/delete/109329/spam
Del: non-english -- https://master.php.net/note/delete/109329/non-english
Del: in docs -- https://master.php.net/note/delete/109329/in+docs
Del: other reasons-- https://master.php.net/note/delete/109329
Reject -- https://master.php.net/note/reject/109329
Search -- https://master.php.net/manage/user-notes.php