php - 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 InfiniteIterator
1, 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)
解决方案
如果不使用迭代器,您可以只使用数组和指向“当前”条目的指针,然后使用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;
}
推荐阅读
- python - 使用 pytest 异常
- reactjs - 未捕获(承诺中)错误:网络错误:位置 3 的 JSON 中的意外令牌 <
- python - FFmpeg 从图像创建视频,从时间戳插入图像作为帧?
- acumatica - 如何在特定位置添加操作菜单
- javascript - 用 jquery 修改自定义 HTML-Attribute 不会影响 CSS
- javascript - 当我选中复选框时,只显示一个值而不是所有值
- javascript - 如何使用 window.open() 下载多个文件?
- android - 有人可以解释 Flutter 中的 Navigator 类和 Scaffold 类吗?
- python - telethon:如何检查消息传递状态?
- nlp - 语法网络中的专长的含义