首页 > 解决方案 > SPL InfiniteIterator is not working with next or prev

问题描述

I wanted to over an array infinitely like a circular array.

I have the following setup using InfiniteIterator1, which iterates over the $players infinitely. But actually, I want to know the next player and the previous player from this loop like below

$players = new InfiniteIterator(new ArrayIterator(['Shobi', 'Jomit']));

foreach ($players as $player) {
    echo $player; // current player name comes properly infinetly
    echo next($players); // next player should come
    echo current($players); // current player should come
    echo prev($players); //previous player should come
}

but next() and prev() always return null

From the doc, I can see those methods are returning void, but is there any way I can extend the InfiniteIterator and achieve this mechanism required?

How do I make next() and prev() work with InfiniteIterator?

Edit current() returns current item, (meaning, it works properly in the logic)

标签: phpiteratorinfinite-loopphp-7.2spl

解决方案


如果不使用迭代器,您可以只使用数组和指向“当前”条目的指针,然后使用while(true)将继续进行的循环(您始终可以添加 abreak来停止它以进行测试或某些条件)。逻辑的各个部分检查当前玩家是否是最后一个 - 所以下一个是开始的 - 或者它是否是第一个项目,所以前一个是结束的项目。此外,增量一旦到达终点就会重置并重新开始......

$players = ['Shobi', 'Jomit'];
$playerKey = 0;
$playerCount = count($players);
while(true) {
    echo $players[($playerKey+1)%$playerCount].PHP_EOL; // next player
    echo $players[$playerKey].PHP_EOL; // current player
    echo $players[($playerKey>0)?$playerKey-1:$playerCount-1].PHP_EOL; //previous player
    $playerKey = ( $playerKey+1 == $playerCount )?0:$playerKey+1;
}

推荐阅读