The below shows that SplPriorityQueue gives highest priority to the largest priority value which, in this case, corresponds to the latest date.
$q=new SplPriorityQueue();
foreach(range(1,5) as $i){
$s='2011-03-' . (1+$i);
$d=date_create($s);
echo $i, ' ', $d->format('Y-m-d'),'<br/>';
$q->insert($i,$d);
}
/*
1 2011-03-02
2 2011-03-03
3 2011-03-04开发者_如何学C
4 2011-03-05
5 2011-03-06
*/
foreach($q as $i){
echo "$i ";
}
//5 4 3 2 1
Given an arbitrary set of dates as priorities, how can one cause SplPriorityQueue's contents to come out in ascending rather than descending date order?
ETA: I've got a kludgy way using Unix timestamps. But that fails outside the Unix era.
$q=new SplPriorityQueue();
foreach(range(1,5) as $i){
$s='2011-03-' . (1+$i);
$d=date_create($s);
$u=$d->format('U');
echo $i, ' ', $d->format('Y-m-d'), ' ',-$u,'<br/>';
$q->insert($i,-$u);
}
/*
1 2011-03-02 -1299038400
2 2011-03-03 -1299124800
3 2011-03-04 -1299211200
4 2011-03-05 -1299297600
5 2011-03-06 -1299384000
*/
foreach($q as $i){
echo "$i ";
}
//1 2 3 4 5
Is there a more robust way?
How about ordering by (99999999- yyyymmdd)?
Having taken a look at the manual, it appears the recommended way to change the sorting is to extend the standard class, and supply your own SplPriorityQueue::compare function.
精彩评论