note 23915 added to function.asort
| From: | phzzzt.a.t.acm.d.o.t.org@php.net | Date: | Wed, 31 Jul 2002 21:15:55 +0000 |
| Subject: | note 23915 added to function.asort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-34081@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>
--
http://www.php.net/manual/en/function.asort.php
http://master.php.net/manage/user-notes.php?action=edit+23915
http://master.php.net/manage/user-notes.php?action=delete+23915
http://master.php.net/manage/user-notes.php?action=reject+23915