PHP 递归目录列表 - 仅目录

标签 php html directory-listing

我正在做一个文件管理器项目,但似乎无法集中精力做一个递归目录列表,而我只得到目录。当我尝试将其解析为我的 jQuery 树的返回结构时,我尝试过的所有内容要么留下空的子目录,要么不起作用。

我尝试过使用数组和递归迭代器,但到目前为止对我来说没有任何效果。

** 更新**

感谢大家的意见,我将我的代码精简为:

class image_management {

private $_user_id;
private $_user_name;
private $_user_path;    

/**
* Constructor
*/
function __construct($user_id, $user_name) {

  $this->_user_id = $user_id;
  $this->_user_name = $user_name;
  $this->_user_path = ORDER_ROOT.$this->_user_id;
}    

/**
* Cleanup the class and close connections
* 
*/
function __destruct() {
}

/**
* Get Image Folders
* Returns an HTML list of the folders under a users
* directory.
*  
* @param hash $user_id -user id hash
* @param string $user_name - users email address
* @return string - html list
*/
public function getHTMLTree() {

  $html = "<li><a href='#'>";
  $html .= $this->_user_name . "</a><ul>";

  $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->_user_path), RecursiveIteratorIterator::SELF_FIRST);
  foreach($objects as $file) {
    if($file->isDir() ) {
      $item = substr($file->getPathname(),strlen($this->_user_path));
      echo $item;
    }
  }
  return $html;
}

这给了我输出:

/home/printshi/public_html/test/orders/88a0a01afd3728af8f6710ed874267f3
/Aggie_Stuff
/Misc
/Misc/Christmas
/Misc/Christmas/santa
/Misc/Christmas/frosty
/Misc/test1
/Geek_Stuff

这让我更接近了,我现在的问题是我需要做的是将所有这些元素包装在 HTML 中,以便我得到如下输出:

<ul>
<li>Aggie_Stuff</li>
<li>Misc<ul>
    <li>Christmas<ul>
        <li>santa</li>
        <li>frosty</li>
        </ul>
    </li>
    <li>test1</li>
    </ul>
<li>Geek_Stuff</li>

我理解的递归部分,它只是让它执行 HTML,无论我如何努力,我似乎​​都无法理解。

最佳答案

看看 DirectoryIterator类,尤其是 isDir功能。

$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
        // recursion goes here.
    }
}

关于PHP 递归目录列表 - 仅目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3153968/

相关文章:

javascript - d3.js 在每个条的末尾堆叠条形图值

php - tidy - 如何从 HTML 中删除重复的 ID

html - 如何在 HTML 中显示 Web 服务器文件列表

powershell - 如何提高计算 N 个最大文件大小的速度和内存使用率?

php - 如何将 MySQL BLOB 转换为 PHP 短裤数组?

php - 如何更改codeigniter中的默认数据库

php - 在 PHP 中获取大文件的 mimetype

javascript - 如何保留文本节点中的空白?

php - 试图计数,但变为 1