note 97261 deleted from function.usort by cmb
| From: | cmb@php.net | Date: | Sun, 13 Oct 2019 08:12:46 +0000 |
| Subject: | note 97261 deleted from function.usort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212626@lists.php.net to get a copy of this message | ||
Note Submitter: nicolas dot demarque at gmail dot com
----
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";
?>