[英]Exploring a file structure using php using scandir()
I am new to php and trying to learn how to navigate a local file structure in for the format: 我是php的新手,正在尝试学习如何导航以下格式的本地文件结构:
-Folder
-SubFolder
-SubSubFolder
-SubSubFolder
-SubFolder
-SubSubFolder
...
From another stackoverflow question I have been able to use this code using scandir(): 关于另一个stackoverflow问题,我已经能够使用scandir()使用以下代码:
<?php
$scan = scandir('Folder');
foreach($scan as $file)
{
if (!is_dir($file))
{
$str = "Folder/".$file;
echo $str;
}
}
?>
This allows me to generate a list of strings of all the 'SubFolder' in my folder directory. 这使我可以在文件夹目录中生成所有“ SubFolder”的字符串列表。
What I am trying to do is list all the 'SubSubFolder' in each 'SubFolder', so that I can create a string of the 'SubSubFolder' name in combination with its 'SubFolder' parent and add it to an array. 我想做的是列出每个“ SubFolder”中的所有“ SubSubFolder”,以便我可以结合其“ SubFolder”父级创建一个“ SubSubFolder”名称的字符串,并将其添加到数组中。
<?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;
}
}
}
}
?>
This however isn't working, and I wasn't sure if it was because I cannot do consecutive scandir() or if I cannot use $file again. 但是,这不起作用,我不确定是否是因为我无法连续执行scandir()还是无法再次使用$ file。
There is probably a better solution, but hopefully the following will be of some help. 可能有更好的解决方案,但希望以下内容会有所帮助。
<?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
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.