public function getNext() { if ($count = count($this->queues)) { $it = new \ArrayIterator($this->queues); $it = new \InfiniteIterator($it); $it = new \LimitIterator($it, $this->nextPos, $count); foreach ($it as $queue) { if ($task = $queue->pop()) { $this->nextPos = ($it->getPosition() + 1) % $count; return $task; } } } return false; }
<?php $it = new LimitIterator(new ArrayIterator(array(1, 2, 3, 4)), 1, 2); foreach ($it as $k => $v) { echo "{$k}=>{$v}\n"; var_dump($it->getPosition()); } try { $it->seek(0); } catch (OutOfBoundsException $e) { echo $e->getMessage() . "\n"; } $it->seek(2); var_dump($it->current()); try { $it->seek(3); } catch (OutOfBoundsException $e) { echo $e->getMessage() . "\n"; } $it->next(); var_dump($it->valid()); ?> ===DONE=== <?php exit(0);
} echo '----------------------------------- CachingIterator END ---------------------------------', '<br />'; echo '--------------------------------- LimitIterator END-----------------------------------', '<br />'; /** * LimitIterator 遍历一个Iterator的限定子集 * 在__construct有两个可选参数:offset 和 count */ $array = array('apple', 'banana', 'cherry', 'damson', 'elderberry'); $fruits = new ArrayIterator($array); $offset = 3; $count = 2; $limitIt = new LimitIterator($fruits, $offset, $count); // 如果增加了offset,那么只有两个数,但是rewind时,节点值不会变成0,而是被截取的值offset。 // getPosition 获得当前节点的位置 $limitIt->rewind(); var_dump($limitIt->getPosition()); foreach ($limitIt as $item) { echo $item, '<br />'; } echo '--------------------------------- LimitIterator START-----------------------------------', '<br />'; echo '----------------------------------- SplFileObject END ---------------------------------', '<br />'; /** * SplFileObject 对文本文件进行遍历 */ $file = '/data/www/test.php'; $fileIt = new SplFileObject($file); // 遍历获得所有的文本,按行遍历 /*foreach ($fileIt AS $item) { echo $item, '<br />'; }*/ // 返回第几行