PHP: Implementing the SeekableIterator Interface

I am currently writing a class that implements the SeekableIterator interface and am facing a problem. I have two internal arrays that I am using and would like to allow iteration through them from outside the class. Is there an easy way to do this without merging the two arrays inside the class? Here's a quick example of what I'm trying to do:

class BookShelf implements ArrayAccess, Countable, SeekableIterator {
    protected $_books = array(...);
    protected $_magazines = array(...);

    /**** CLASS CONTENT HERE ****/
}

$shelf = new BookShelf();

// Loops through both arrays, first books (if any) and then magazines (if any)
foreach($shelf as $item) {
    echo $item;
}

      

+1


source to share


1 answer


Assuming these arrays are numerically indexed if the current index is less than

count($this->_books);

      

then return

$this->_books[$index];

      



Otherwise, if the index is less than count (books) + count (journals), return

$this->_magazines[$index-count($this->_books)]

      

Otherwise, an OutOfBoundsEx exception might be ok.

Everything else should just fall into place.

+1


source







All Articles