PHP convert Multidimensional Array of directories into strings

Viewed 106

I get stuck with recursion functions and I couldn't find anything that would quite do what I need, so I'm hoping someone can help me with this. I've got a multidimensional array of directories for a given drive and I need to convert them into full path strings for EACH deepest subdirectory. Here's the array:

<?php
$array = array(
'CANON' => array(
    'DCIM' => array(
        '100CANON',
        '101CANON',
        'CANONMSC'
    ),
    'CANON_SC' => array(
        'IMAGE' => array(
            '0001'
        ),
        'DOCUMENT' => array(
            '0001'
        ),
    ),
    'MISC'
));

Here's the desired output:

/CANON/DCIM/100CANON/
/CANON/DCIM/101CANON/
/CANON/DCIM/CANONMSC/
/CANON/CANON_SC/IMAGE/0001/
/CANON/CANON_SC/DOCUMENT/0001/
/CANON/MISC/

This is what I have so far, but it only works for the first deepest directory and ignores the sibling directories.

<?php
function flatten_directory($array, $prefix = '')
{
    $result = '';

    foreach($array as $key=>$value)
    {
        if(is_array($value))
        {
            $result .= $key .'/'. flatten_directory($value, $prefix . $key . '.');
        }
        else
        {
            $result .= $prefix . $key . $value;
        }
    }
    return $result;
}

Thank you in advance.

2 Answers
Related