Thursday, September 10, 2009

PHP directory listing : convert a folder tree into an array

Hi there!

in a post few months ago i talked about Directory listing in php, there i show a pair of function to list a directory and turn it into an array.

Well today i come back to that function and change it a little to get it better.

It's quite simple, it start from a path (btw thinking correct) and push it into a structured array. In wich every array element mean a subdirectory, and a null value mean a file.

You can choose the recursive mode in which, when a subfolder is found goes deep into it (recursively too) to fill the array with file and subfolder of that directory.

It's simple, it just check the params $recurrent for true and that the "entry" scaned by read method from metaclass dir is a directory.

Hope someone could find it useful.


function array_converter($path, $recurrent = false, $tree = array())
{
$path = realpath($path);
$d = dir($path);
while(false != ($entry = $d->read()))
{
$complete = $d->path."/".$entry;
if(is_dir($complete) && $entry !== '.' && $entry !== '..')
{
$tree[$entry] = array();
if($recurrent && $entry !== '.' && $entry !== '..')
{
$tree[$entry] = array_converter($complete, $recurrent, $tree[$path][$entry]);
}
} elseif($entry !== '.' && $entry !== '..') {
$tree[$entry] = null;
}
}
$d->close();
return $tree;
}