Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 10 ■ SPL ITERATORS^147

4567

This iterator can be extremely useful for paginated display of a dataset.

AppendIterator
The AppendIterator allows you to sequentially iterate several different iterators. For example,
if you wanted to iterate two or more arrays in a single loop, you would use the AppendIterator.
Listing 10-4 shows how to use the AppendIterator.

Listing 10-4. Using an AppendIterator Iterator

$arrFirst = new ArrayIterator(array(1,2,3));
$arrSecond = new ArrayIterator(array(4,5,6));

$iterator = new AppendIterator();
$iterator->append($arrFirst);
$iterator->append($arrSecond);

foreach($iterator as $number) {
echo $number;
}

123456

As you can see, the order in which the iterators are appended is the order in which they
were iterated. Because an AppendIterator was used, only one loop was needed to iterate over
both arrays.
This iterator is highly useful for aggregating data from multiple sources into a single iter-
ator. You could use array_merge() to join arrays; however, using the iterator approach gives
you the ability to use the features of any of the iterators described in this section in combina-
tion. Listing 10-5 shows how you would use the LimitIterator, AppendIterator, and iterator_
to_array() to create an array consisting of the first two elements of each input array.

Listing 10-5. Advanced Array Merging

$arrFirst = new ArrayIterator(array(1,2,3));
$arrSecond = new ArrayIterator(array(4,5,6));

$iterator = new AppendIterator();
$iterator->append(new LimitIterator($arrFirst, 0, 2));
$iterator->append(new LimitIterator($arrSecond, 0, 2));
print_r(iterator_to_array($iterator, false));

McArthur_819-9C10.fm Page 147 Friday, February 22, 2008 9:08 AM

Free download pdf