note 54922 deleted from ref.dir by sniper
| From: | sniper@php.net | Date: | Thu, 15 Dec 2005 23:59:08 +0000 |
| Subject: | note 54922 deleted from ref.dir by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-100240@lists.php.net to get a copy of this message | ||
Note Submitter: peterdolan at antispamalicious dot jps dot net
----
A quick recursive function I came up with to return the directory tree and files under a particular
path in an associative array.
For a file such as /the/directory/you/want/thefile.foo,
$tree["the"]["directory"]["you"]["want"][0] =
"thefile.foo"
I needed it for a hacktastic way of storing variables temporarily in a directory structure. YMMV.
<?php
/*---------- Directory Tree to Array ----------//
Takes base directory, returns an associative array
containing each directory name as an associative key
and each file as an indexed entry in the appropriate
directory.
If no path is provided, it uses the current directory
If $style == 1, it will return a sorted, non-associative
array
//-----------------------------------------------------------*/
function dirTreeToArray( $path = "./", $style="0" ) {
if ( !is_array($path) or !($style==0 or $style==1) ) die("Improper arguments in function
dirTreeToArray(string \$path, \$style = {0, 1})");
$tree = array();
$arrayPointer = & $tree;
if ( $handle = opendir($path) ) {
while ( $fileName = readdir($handle) ) {
if ( $fileName != "." and $fileName != ".." ) {
$newPath = "$path/$fileName"; // Used for testing directory or
file property
if ( is_dir($newPath) ) {
$dummyPointer = & $arrayPointer; // Save the current pointer
if ( $style == 0 ) $arrayPointer = & $arrayPointer[$fileName]; // Drop the pointer into a
subdirectory
elseif ( $style == 1 ) $arrayPointer = & $arrayPointer[]; // Drop the pointer into a
subdirectory
$arrayPointer = dirTreeToArray($newPath, $style); // Process the new subdirectory
if ( $style == 1 ) sort($arrayPointer); // Sort it if we're in a non-associative mode
$arrayPointer = & $dummyPointer; // Bring the pointer back up a level
}
elseif ( is_file($newPath) ) $arrayPointer[] = $fileName; // Enter the files
}
}
return $tree;
}
else die("Failed to open directory $path in function dirTreeToArray(string \$path, \$style =
{0, 1})");
}
?>