用于遍历目录/文件树和输出树作为嵌套 UL 的 PHP 脚本

标签 php html arrays recursion directory

<分区>

我有目录、子目录和文件(在一些但不是所有目录中)的树。这是整棵树的示例:

/food
/food/drinks
/food/drinks/water.html
/food/drinks/milk.html
/food/drinks/soda.html
/food/entrees
/food/entrees/hot
/food/entrees/hot/hamburger.html
/food/entrees/hot/pizza.html
/food/entrees/cold
/food/entrees/cold/icecream.html
/food/entrees/cold/salad.html
/cosmetics
/cosmetics/perfume
/cosmetics/perfume/chic.html
/cosmetics/perfume/polo.html
/cosmetics/perfume/lust.html
/cosmetics/lipstick
/cosmetics/lipstick/colors
/cosmetics/lipstick/colors/red.html
/cosmetics/lipstick/colors/pink.html
/cosmetics/lipstick/colors/purple.html

好的,从“/”目录中的 php 脚本,我想递归或遍历此目录树并像这样打印树:

<ul>
  <li>food</li>
    <ul>
      <li>drinks</li>
        <ul>
          <li>water.html</li>
          <li>milk.html</li>
          <li>soda.html</li>
        </ul>
      <li>entrees</li>
        <ul>
          <li>hot</li>
            <ul>
              <li>hamburger.html</li>
              <li>pizza.html</li>
            </ul>
          <li>cold</li>
            <ul>
              <li>icecream.html</li>
              <li>salad.html</li>
            </ul>      
        </ul>
    </ul>
  <li>cosmetics</li>
    <ul>
      <li>perfume</li>
        <ul>
          <li>chic.html</li>
          <li>polo.html</li>
          <li>lust.html</li>
        </ul>
      <li>lipstick</li>
        <ul>
          <li>colors</li>
            <ul>
              <li>red.html</li>
              <li>pink.html</li>
              <li>purple.html</li>
            </ul>
        </ul>
    </ul>
</ul>

最佳答案

我认为您在这里需要的是 RecursiveDirectoryIterator来自 PHP Standard Library (SPL)

然后你可以写类似下面的东西:

function iterateDirectory($i)
{
    echo '<ul>';
    foreach ($i as $path) {
        if ($path->isDir())
        {
            echo '<li>';
            iterateDirectory($path);
            echo '</li>';
        }
        else
        {
            echo '<li>'.$path.'</li>';
        }
    }
    echo '</ul>';
}

$dir = '/food';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

iterateDirectory($iterator);

关于用于遍历目录/文件树和输出树作为嵌套 UL 的 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748387/

相关文章:

php - 使用 php mysql 创建嵌套的 json 对象

php - 排序 multidim 数组 : prioritize if column contains substring, 然后按第二列排序

php - mysql_fetch_array 加 undefined variable 的 RSS 提要问题

c# - 将值传递给 html 从后面的代码中选择

html - 响应式设计,最大宽度不起作用

arrays - 如何在 Flutter 的 Firestore 中向数组添加相等的元素?

java - 矩阵中的最大值

php - 使用连接表对 mysql 结果进行分组

html - 右对齐的选项卡在侧面有一个不需要的间隙

arrays - 如何在 Ruby 中迭代哈希数组并返回字符串中特定键的所有值