note 109329 modified in function.usort by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:45:09 +0000 |
| Subject: | note 109329 modified in function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189220@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); ?>
--was--
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);
http://php.net/manual/en/function.usort.php