![](/img/trans.png)
[英]What is the difference between SplObjectStorage::contains and SplObjectStorage::offsetExists?
[英]Reverse SPLObjectStorage
我有一個SPLObjectStorage對象,其中有一個Player對象作為鍵,並獲得了與之關聯的信息的分數。 播放器對象按照從最高得分到最低得分的順序添加到存儲中,但是現在我需要以相反的順序遍歷它們。
我還需要能夠從指定的偏移量開始一直循環。 我已經在下面找到了這一部分,但我只是想不出一個先將其反轉的好方法。
// $players_group = new SPLObjectStorage()
// code to add Player and Score would go here
// above lines just for example
# NEED TO REVERSE ORDER PLAYERS GROUP HERE
$infinite_it = new InfiniteIterator($players_group);
$limit_it = new LimitIterator($infinite_it, $current_offset, $players_group->count());
foreach($limit_it as $p){
// properly outputting from offset all the way around
// but I need it in reverse order
}
我想避免必須遍歷存儲對象並將它們全部推入數組,然后執行array_reverse,然后最后進行我的foreach循環。
SplObjectStorage
是key->value store
並且SplObjectStorage
元素的“鍵”實際上是對象的哈希。 排序和還原需要您擴展和編寫自己的實現,但我認為您應該考慮使用SplStack
想象一下您的球員職業
class Player {
private $name;
function __construct($name) {
$this->name = $name;
}
function __toString() {
return $this->name;
}
}
使用SplStack
$group = new SplStack();
$group->push(new Player("Z"));
$group->push(new Player("A"));
$group->push(new Player("B"));
$group->push(new Player("C"));
echo "<pre>";
$infinite_it = new InfiniteIterator($group);
$limit_it = new LimitIterator($infinite_it, 0, 3); // get frist 3
foreach ( $limit_it as $p ) {
echo ("$p");
}
如果您堅持使用SplObjectStorage
則可以考慮使用自定義ReverseArrayIterator
class ReverseArrayIterator extends ArrayIterator {
public function __construct(Iterator $it) {
parent::__construct(array_reverse(iterator_to_array($it)));
}
}
用法
$group = new SplObjectStorage();
$group->attach(new Player("Z"));
$group->attach(new Player("A"));
$group->attach(new Player("B"));
$group->attach(new Player("C"));
echo "<pre>";
$infinite_it = new InfiniteIterator(new ReverseArrayIterator($group));
$limit_it = new LimitIterator($infinite_it, 0, 3); // get frist 3
foreach ( $limit_it as $p ) {
echo ("$p");
}
兩者都會輸出
CBA //reversed
我想避免必須遍歷存儲對象並將它們全部推入數組,然后執行array_reverse,然后最后進行我的foreach循環。
不知道這是否是最有效的方法,但是當SplObjectStorage實現Iterator時,您可以使用iterator_to_array然后反轉數組:
array_reverse(iterator_to_array($players_group));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.