簡體   English   中英

使用scandir()使用php探索文件結構

[英]Exploring a file structure using php using scandir()

我是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”父級創建一個“ 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;
            }
        }
    }
}
?>

但是,這不起作用,我不確定是否是因為我無法連續執行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( '&nbsp;', ( $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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM