You can use a stack and skip recursion. If you add the child elements in reverse order to the stack, then you should get the same order as your recursive version. If order doesn't really matter, then there's no need to reverse the iteration.
You don't really have to understand the meaning of the output (as it has none), but just focus on rewriting your recurse
function into an iter
function.
<?php
function getObj($n)
{
return $n ? new Foo($n) : null;
}
class Foo implements IteratorAggregate
{
public $n;
public function __construct($n)
{
$this->n = $n;
}
public function getIterator()
{
$values = [];
for ($i = 0; $i < $this->n; ++$i)
{
$values[] = (int) ($i / 2);
}
return new ArrayIterator($values);
}
}
function recurse($n)
{
$obj = getObj($n);
if ($obj)
{
echo "n => ", $obj->n, "\n";
foreach ($obj as $val)
{
recurse($val);
}
}
}
function iter($n)
{
$stack = [];
$obj = getObj($n);
if ($obj)
{
$stack[] = $obj;
}
while ($stack)
{
$obj = array_pop($stack);
echo "n => ", $obj->n, "\n";
foreach (array_reverse(iterator_to_array($obj)) as $val)
{
$obj = getObj($val);
if ($obj)
{
$stack[] = $obj;
}
}
}
}
recurse(10);
echo "-----\n";
iter(10);
Note that they give the same output, although if getObj()
has any side-effects, things may be different between the two.