【发布时间】:2021-09-12 02:25:33
【问题描述】:
我发现continue 功能只能通过递归在迭代器模式中实现。
问题当然是循环数百万个应继续的无效元素应该非常慢或堆栈溢出。
如何在不使用迭代器模式内递归的情况下实现continue关键字?
带有递归的 PHP 代码:
class TableIterator implements \Iterator
{
private $row;
private $fileLines;
public function __construct()
{
$this->fileLines = [
"1, 2, 3, 4, 5, 6, 7, 8",
"my condition, 9, 10, 11, 12, 13, 14, 15",
"my condition, 16, 17, 18, 19, 20, 21, 22, 23",
"24, 25, 26, 27, 28, 29, 30, 31",
"32, 33, 34, 35, 36, 37, my condition 2, 38",
"39, 40, 41, 42, 43, 44, 45, 46"
];
}
public function rewind(): void
{
reset($this->fileLines);
}
public function current(): array
{
return $this->row;
}
public function key(): int
{
return key($this->fileLines);
}
public function next(): void
{
next($this->fileLines);
}
public function valid(): bool
{
$this->row = explode(", ", current($this->fileLines));
if($this->row[0] === 'my condition')
$this->continue(); // here is the recursion problem
if($this->row[6] === 'my condition 2')
return false;
return true;
}
private function continue()
{
$this->next();
$this->valid();
}
}
foreach(new TableIterator() as $key => $value)
print_r($value);
如果有 PHP 的解决方案或 hack,我会很高兴。 谢谢。
【问题讨论】: