gpt4 book ai didi

php - 反向 SPLObjectStorage

转载 作者:行者123 更新时间:2023-12-02 22:18:39 27 4
gpt4 key购买 nike

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

关于php - 反向 SPLObjectStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14080409/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com