如何循环遍历子目录


How do I loop through subdirectories?

我主要在000webhost.com上使用php。新手或初学者。我从youtube和developphp.com上学到了大部分知识。

好,我的问题是。我试图在不使用flash的情况下建立一个动态画廊页面。它必须是动态的,因为我想要一个用户能够上传一张图片,然后有它显示在画廊页面。到目前为止一切顺利。我正在寻找某种foreach (is_dir(/Albums/))调用来循环我的相册目录并查找所有文件夹,然后将它们添加到页面。现在我必须手动输入所有的东西。这就是它的样子。

<table width="100%"><tr><td width="78%"><span class="textbg">Miller Albums</span></td><td width="22%"><?php echo $toplinks; ?></td></tr></table><span class="textsm"></span><p class="desc"></p><p><span class="textreg">Click an album to see the pictures</span><br><a href="http://miller.netai.net/member_profile.php?id=<?php echo $id; ?>">Home</a>
</p><hr size="1">
<table style="text-align: center">
<tbody>
<tr>
<td>
<a href="/Albums/CRFA"><img width="150" height="150" border="0" align="middle" title="CRFA" src="/Albums/CRFA/thumbnail.jpg"></a>
</td>
<td>
<a href="/Albums/Internet%20Pics"><img width="150" height="150" border="0" align="middle" title="Internet Pics" src="/Albums/Internet%20Pics/thumbnail.jpg"></a>
</td>
<td>
<a href="/Albums/Dads%20Wedding"><img width="150" height="150" border="0" align="middle" title="Dads Wedding" src="/Albums/Dads Wedding/thumbnail.jpg"></a>
</td>
<td>
<a href="/Albums/Dads%20Wedding%20(cont.)"><img width="150" height="150" border="0" align="middle" title="Dads Wedding (cont.)" src="/Albums/Dads Wedding (cont.)/thumbnail.jpg"></a>
</td>
</tr>
<tr>
<td>
<label><font size="3">Ben's Fire Academy</font></label>
</td>
<td>
<label><font size="3">Internet Pics</font></label>
</td>
<td>
<label><font size="3">Dad's Wedding</font></label>
</td>
<td>
<label><font size="3">Dad's Weding (cont.)</font></label>
</td>
</tr></tbody></table>
<map name="Map">
<area href="frameset.htm" coords="95,1,129,44" shape="rect">
</map>
</body>

我想在身体里有一些东西,比如……

 <table style="text-align: center">
        <tbody>
        <tr>
<?php
foreach(is_dir(/Albums/))
    <td>
    <a href="/Albums/%dir%">
    <img width="150 height="150" border="0" align="middle" title="%dir%" src="/Albums/%dir%/thumbnail.jpg"></a>
    </td>
IF no_more_dir
    exit();
?>
        </tr> 

有办法做这件事吗?还是我在我的头上?

您可以使用DirectoryIterator

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if($fileInfo->isDir() && !$fileInfo->isDot()) {
        // Do whatever
    }
}

你做对了!

这是你需要它做的:http://php.net/manual/en/class.recursivedirectoryiterator.php

$album_dir = new RecursiveDirectoryIterator('path/to/album_root');
foreach (new RecursiveIteratorIterator($album_dir) as $filename => $file) {
    // echo img tag
}

虽然我很喜欢使用迭代器,但另一种选择是使用。

获取一个文件夹数组。
glob('path/to/albums/*', GLOB_DIR)

如果你想用迭代器,那么ParentIterator就派上用场了,它可以很容易地只迭代目录。

$dirs = new ParentIterator(new RecursiveDirectoryIterator('path/to/albums'););
$it  = new RecursiveIteratorIterator($dirs, RecursiveIteratorIterator::SELF_FIRST);
// Optionally, limit the depth of recursion with $it->setMaxDepth($number)
foreach ($it as $dir) {
    // Output your HTML here
}