note 97261 added to function.usort
| From: | nicolas dot demarque at gmail dot com | Date: | Sat, 10 Apr 2010 18:37:09 +0000 |
| Subject: | note 97261 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168111@lists.php.net to get a copy of this message | ||
Another way to compare object is to have a compare static function in the class with reccursion
ability and have globals or static variables who save the state of comparison, and the order.
It could be a good idea to have a variable with comparison functions name (with the sorting :
numeric, alphanumeric, inverse).
<?php
interface Comparable{static function compare($a, $b);}
class myObj implements Comparable{
var $var1; var $var2; var $var3;
function __construct($v1, $v2, $v3){
$this->var1=$v1; $this->var2=$v2; $this->var3=$v3;
}
public function __toString() {
return "v1 ".$this->var1." v2 ".$this->var2." v3
".$this->var3;
}
static function compare($a, $b){
$sort=$GLOBALS['sorts'][$GLOBALS['sort']];
echo "$sort\n";
if($a->$sort == $b->$sort){
if($GLOBALS['sorts'][$GLOBALS['sort']+1]){
$GLOBALS['sort']++;
$res= call_user_func(array('myObj', 'compare'),
$a, $b);
$GLOBALS['sort']=0; return $res;
}
$GLOBALS['sort']=0; return 0;
}
$GLOBALS['sort']=0;
if($a->$sort > $b->$sort)
return 1;
return -1;
}
}
$objects = array(new myObj("1", "2", "3"), new myObj("2",
"2", "2"), new myObj("1", "3", "4"));
/* Tests */
$sorts=Array('var1', 'var2', 'var3'); $sort = 0; usort($objects,
array('myObj', 'compare')); echo ("var1 var2 var3\n");
foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var3', 'var1'); $sort = 0; usort($objects,
array('myObj', 'compare')); echo ("\nvar2 var3 var1\n");
foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var1', 'var3'); $sort = 0; usort($objects,
array('myObj', 'compare')); echo ("\nvar2 var1 var3\n");
foreach($objects as $o)echo $o."\n";
?>
----
Server IP: 89.31.146.176
Probable Submitter: 188.73.38.212
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/97261
Del: integrated -- https://master.php.net/note/delete/97261/integrated
Del: useless -- https://master.php.net/note/delete/97261/useless
Del: bad code -- https://master.php.net/note/delete/97261/bad+code
Del: spam -- https://master.php.net/note/delete/97261/spam
Del: non-english -- https://master.php.net/note/delete/97261/non-english
Del: in docs -- https://master.php.net/note/delete/97261/in+docs
Del: other reasons-- https://master.php.net/note/delete/97261
Reject -- https://master.php.net/note/reject/97261
Search -- https://master.php.net/manage/user-notes.php