反转SPLObjectStorage

时间:2012-12-29 09:35:50

标签: php spl

我有一个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循环。

2 个答案:

答案 0 :(得分:2)

  

我想避免必须遍历存储对象并将它们全部推入数组,然后执行array_reverse,然后最后继续我的foreach循环。

不知道它是否是最有效的方法,但是当SplObjectStorage实现Iterator时,你可以使用iterator_to_array然后反转数组:

array_reverse(iterator_to_array($players_group));

答案 1 :(得分:2)

SplObjectStoragekey->value storeSplObjectStorage中元素的“关键字”实际上是对象的哈希值。排序和还原需要您扩展和编写自己的实现,但我认为您应该考虑使用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