This post is going to serve as a place to point people to, as it is a question that gets asked fairly regularly in the PHP support channels that I hang around in. The task is to “flatten” nested arrays into a single series containing all of the values.
Example input array
Expected output array
It looks like most people usually resort to a function that calls itself recursively to build the output array. My two examples below will give the expected output array, but will let PHP take care of the recursion for us.
Iterator, Iterator, Iterator, Iterator
This is my preferred way. OK, sure it creates a hierarchy of objects only to mush the values into an array, but it’s nice and concise. Besides, anyone who knows me knows I’m a fan of the SPL.
new RecursiveArrayIterator($input)), FALSE);
Walking the array recursively
This is a more procedural approach, but again it saves us from thinking about the recursion. It uses a closure to build up the array step by step.