From the course: Learning the Standard PHP Library

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Using multidimensional arrays with iterators

Using multidimensional arrays with iterators - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Using multidimensional arrays with iterators

- The SPL iterator for multidimensional arrays is called rather predictably, RecursiveArrayIterator. To demonstrate how it works, I've opened recursive_array.php, which you can find in the Chapter Four folder of the exercise files. It contains a multidimensional associative array called, "Products." So let's convert this into an Iterator. We'll keep the same name, "products," "new," "RecursiveArrayIterator," and we pass it the array, which is called, "products." Because it's recursive, we need to use RecursiveIteratorIterator, so "products," "new," "RecursiveIteratorIterator," and we pass it our "products" Iterator. And we're dealing with an associative array, so we need both the parents and the children. By default, RecursiveIteratorIterator only gets the children, so we need to reset the mode to SELF_FIRST. So that's the second argument to RecursiveIteratorIterator. It's a class constant, so "RecursiveIteratorIterator," then SELF_FIRST. So we can now use a foreach loop to go over…

Contents