Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have an array containing full paths of files. Like this:

[0] => "dir1/dir2/dir3/file.ext"
[1] => "dir1/dir2/dir3/file2.ext"
[2] => "dir1/dir2/dir3/file3.ext"
[3] => "dir2/dir4/dir5/file.ext"

I need to parse it and get a multidimensional array, something like this:

[dir1] => [dir2] => [dir3] => file.ext
                           => file2.ext
                           => file3.ext
[dir2] => [dir4] => [dir5] => file.ext

Any ideas? Must work with various depth of the structure.

share|improve this question
2  
This question talks about something almost identical to what you need. – Jon Sep 16 '12 at 16:06
up vote 1 down vote accepted

I've done your homework! :-)

http://ideone.com/UhEwd

Code:

<?php

function parse_paths_of_files($array)
{
    $result = array();

    foreach ($array as $item)
    {
        $parts = explode('/', $item);
        $current = &$result;
        for ($i = 1, $max = count($parts); $i < $max; $i++)
        {
            if (!isset($current[$parts[$i-1]]))
            {
                 $current[$parts[$i-1]] = array();
            }
            $current = &$current[$parts[$i-1]];
        }
        $current[] = $parts[$i];
    }

    return $result;
}

$test = array(
    "dir1/dir2/dir3/file.ext",
    "dir1/dir2/dir3/file2.ext",
    "dir1/dir2/dir3/file3.ext",
    "dir2/dir4/dir5/file.ext"
);

print_r(parse_paths_of_files($test));

?>
share|improve this answer
    
Oh man, this is awesome. Thanks a lot. You save me. – Koga Sep 16 '12 at 19:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.