2016-06-21 86 views
-1

我花(垃圾)2天,这种可怕的代码(即可能有一些错误)扫描所有的目录和文件的顺序PHP

$diretc [] = ('../documentos'); 
    $txt = ""; 

    function getDirContents($diret){ 
     for ($i=0; $i <sizeof($diret) ; $i++) { 
      $dir = $diret[$i]; 
      if(is_dir($dir)){ //lee si es un directorio 
       $GLOBALS['txt'] .= '<ul>'.$dir; 
       while(($archivo = readdir($dir)) !== false){ 
        if (is_dir($archivo)) { 
         $directorios[] = $archivo; 
        } 
        else if ($archivo != "." && $archivo != "..") { 
         $GLOBALS['txt'] .= '<li>'.$dir.DIRECTORY_SEPARATOR.$archivo.'</li>'; 
        } 
       } 
       $GLOBALS['txt'] .='</ul>'; 
      } 
     } 
     if (sizeof($directorios) > 0) { 
      getDirContents($directorios); 
     } 
     return $txt;  
    } 





echo getDirContents($diretc); 

我试着列出与他们的文件每个目录在我的道路documentos我想通过订单,像文件管理器,像一棵树像this

+0

那么究竟是如何不工作? –

+0

用'$ txt'替换每个$ GLOBALS ['txt']'。 '$ diret'应该是一个不是数组的字符串 – 2016-06-21 21:34:02

+0

@Ini&Dagon:但是不要忘记在函数中放置'global $ txt;'。 –

回答

0

试图帮助。请尝试下面的代码。

function listDir($path, $recursive = false) { 
    $recursive = ($recursive === true); 
    $invalidPaths = array('.', '..'); 
    $valid = is_dir($path); 
    if ($valid !== true) { 
     return array(); 
    } 
    $array = array(); 
    foreach(scandir($path) as $file) { 
     // Check for invalid paths 
     $invalid = in_array($file, $invalidPaths); 
     if ($invalid === true) { 
      continue; 
     } 
     // Format and add file 
     $filename = "$path/$file"; 
     array_push($array, $filename); 

     // Check for read dir recursive 
     $isDirectory = is_dir($file); 
     if ($isDirectory && !$recursive) { 
      continue; 
     } 

     // Add itens 
     $subDirArray = listDir($filename, $recursive); 
     $array = array_merge($array, $subDirArray); 
    } 
    return $array; 
} 

$path = '../documentos'; 
$pathList = listDir($path, true); 
foreach($pathList as $item) { 
    echo "<pre>$item</pre>"; 
} 
相关问题