0

Is it possible to add a new iterator to an AppendIterator while iterating? What I would like to do is to iterate to a result from an api-call. When there is no more items in the result I want to check if I can fetch another result from the api.

I can do this in a simple way implementing the Iterator interface and hold the logic in the valid()-method, but I would like to seperate the item iterator (iterates over each item in a response) and a response iterator (iterate over one or many responses of item iterators).

The only examples I find of AppendIterator appends all iterators before the iteration phase.

When I've tried to implement it myself with an overloaded AppendIterator I either get stuck in an infinite loop or can't traverse to the next item (the first item of the second Iterator)

1 Answers1

2

Yes, you can.

$array = [1,2,3];
$iterator = new AppendIterator ();
$iterator->append(new ArrayIterator($array));

foreach ($iterator as $i)
{
    echo $i, "\n";
    if ($i == 2)
    {
        $iterator->append(new ArrayIterator([6,7,8]));
    }
}

This shows me: 1 2 3 6 7 8

akond
  • 15,865
  • 4
  • 35
  • 55