OK is a bit overworking for this problem, but perhaps it serves some educational purposes. PHP comes with a set of iterators that can be used to abstract iterate over a given set of elements.
class ActorIterator extends FilterIterator { public function accept() { return $this->current()->job == 'Actor'; } } $maxCount = 3; $actors = new LimitIterator( new ActorIterator( new ArrayIterator($movies[0]->cast) ), 0, $maxCount ); foreach ($actors as $actor) { echo ; }
Extending the abstract FilterIterator class, we can define a filter that returns only participants from this list. LimitIterator allows LimitIterator to limit the iteration to a given set and ArrayIterator is a simple helper to make native arrays compatible with the Iterator interface. Iterators allow the developer to create chains that define the iteration process, which makes them extremely flexible and powerful.
As I said in the introduction: this problem can be easily solved without this Iterator material, but it provides the developer with some advanced options and allows you to reuse the code. You could, for example, upgrade ActorIterator to some CastIterator , which allows you to pass the type of fill to filter in the constructor.
Stefan gehrig
source share