我是php新手,正在尝试学习如何导航本地文件结构的格式:
-Folder
-SubFolder
-SubSubFolder
-SubSubFolder
-SubFolder
-SubSubFolder
...
从另一个stackoverflow问题,我已经能够使用这个代码使用scandir():
<?php
$scan = scandir('Folder');
foreach($scan as $file)
{
if (!is_dir($file))
{
$str = "Folder/".$file;
echo $str;
}
}
?>
这允许我生成我的文件夹目录中所有'SubFolder'的字符串列表。
我要做的是列出每个'SubFolder'中的所有'SubSubFolder',这样我就可以创建一个'SubFolder'名称的字符串与其'SubFolder'父级组合并将其添加到数组中。
<?php
$scan = scandir('Folder');
foreach($scan as $file)
{
if (!is_dir($file))
{
$str = "Folder/".$file;
//echo $str;
$scan2 = scandir($str);
foreach($scan2 as $file){
if (!is_dir($file))
{
echo "Folder/SubFolder/".$file;
}
}
}
}
?>
然而,这是不工作,我不确定这是因为我不能做连续的scandir()或如果我不能再次使用$file。
可能有更好的解决方案,但希望以下内容能有所帮助。
<?php
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = @opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces -$file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
//To list folders names only and not the files within comment out the following line.
echo "$spaces $file<br />.";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
getDirectory( "folder" );
// Get the current directory
?>