PHP: Pathable RecursiveIteratorIterator

Published:

Needed to recursively loop through a multi-dimensional array and print out each leaf-node with its full "path".

For this I used a RecursiveArrayIterator for the array and a RecursiveIteratorIterator for the recursion. Thought I was home free because I had used a method called getSubpathname before, but turned out that was just something the RecursiveDirectoryIterator had...

So, had to grow my own... noting it here for others and the future:

class PathableRecursiveIteratorIterator
    extends RecursiveIteratorIterator
{
    /**
     * Gets the path to current node, i.e. each
     *   key "upwards", including self.
     *
     * @param null|string $glue Optional $glue for implode().
     *
     * @return array|string The keys, from root to self,
     *   as an array; or as a string if $glue is provided.
     */
    public function getPath($glue = null)
    {
        for($i = 0; $i < $this->getDepth(); $i++)
            $path[] = $this->getSubIterator($i)->key();

        $path[] = $this->key();

        return $glue !== null
            ? implode($glue, $path)
            : $path;
    }
}