note 23915 deleted from function.asort by dams
| From: | dams@php.net | Date: | Fri, 02 Aug 2002 10:46:33 +0000 |
| Subject: | note 23915 deleted from function.asort by dams | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-34134@lists.php.net to get a copy of this message | ||
This does everything the above casort does, with the benefit of not
resetting keys. ( The above casort dies on weird indexes such as $x['a'],
and it requires you to have everything numbered from [0]..[n] )
It also allows you to plug in your own comparison function.
I've fallen in love with uasort and uksort, they are the bomb. You can
sort ANYTHING with them. :)
The only difference between 'aosort' and the built-in sort functions is the sorted array
is returned, rather than sorted in place, this is b/c php only supports pass by value, there is no
pass by reference (yet?).
THE CODE:
<pre><?
// aosort - object sort
// by default this sorts case insensitively on strings
// use the comparison function to sort according to your needs.
function aosort($x,$var,$cmp='strcasecmp'){
uasort($x,
create_function('$a,$b',
'return '.$cmp.'( $a->'.$var.',$b->'.$var.');')
);
return $x;
}
// Feature Test
function myLess($y,$z)
{ if ($y) return $y < $z; else return 0; };
class Bob{ var $x; var $y;
function Bob($x,$y){$this->x=$x;$this->y=$y;}
function getX(){return $this->x;}
function getY(){return $this->y;}
}
$it[2] = new Bob(2,'az');
$it[4] = new Bob(3,'Ad');
$it[6] = new Bob(1,'ab');
print_r($it);
$it = aosort($it,'getY()');
print_r($it);
$it = aosort($it,'getX()','myLess');
print_r($it);
?></pre>