我是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;
}
}
?>
这允许我生成所有&#39; SubFolder&#39;的字符串列表。在我的文件夹目录中。
我要做的是列出所有&#39; SubSubFolder&#39;在每个子文件夹中,以便我可以创建一个&#39; SubSubFolder&#39;名称与其&#39; SubFolder&#39;组合使用parent并将其添加到数组中。
<?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。
答案 0 :(得分:1)
可能有更好的解决方案,但希望以下内容会有所帮助。
<?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
?>