Janith Chinthana
Janith Chinthana

Reputation: 3844

File structure to multidimensional array

I need to store all directories and files in multidimensional array for a given location (sample : /path/to/folder) . It should include the sub folders as well no matter how deep.

Edited :

I tried with php scandir and it gave me following results,

code :

$dir    = '/path/to/folder';
$files = scandir($dir);
print_r($files);

results :

Array
(
    [0] => .
    [1] => ..
    [2] => folder1
    [3] => file1
    .....
)

What I need is to get the content inside the folder1 and do it continuously till I get complete folder structure with all files.

P.S : I need to remove "." and ".." from the result array too.

Upvotes: 2

Views: 2413

Answers (1)

Janith Chinthana
Janith Chinthana

Reputation: 3844

for file listing php provide readdir and scandir functions.

I preferred sccandir since it's new(php 5>) and we can use following recursive function for this.

Need to provide the directory path (/path/to/your/folder) as a parameter and it will return multidimensional array with folder structure.

function dirToArray($dir) {
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
        if (!in_array($value,array(".","..")))  {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
                $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
            } else {
                $result[] = $value;
            }
        }
    }
    return $result;
}

Upvotes: 11

Related Questions