我有一个 FOR 循环,列出了某个目录中的所有文件。结果之一也是索引。PHP,我不需要的结果。这是循环的第一个结果/条目...
有没有办法跳过第一个结果并从第二个结果开始循环?请帮忙。
<?php
$myDirectory = opendir('.');
while($entryName = readdir($myDirectory))
{
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
echo '<h5>There are ' . $indexCount . ' files in the Media Center</h5>';
sort($dirArray);
echo '<table width="100%">';
echo '<tr>';
echo '<th width="33%" align="center" class="admin_th" style="border-radius: 10px 0 0 0">Download</th>';
echo '<th width="33%" align="center" class="admin_th">Filetype</th>';
echo '<th width="33%" align="center" class="admin_th" style="border-radius: 0 10px 0 0">Filesize (in bytes)</th>';
echo '</tr>';
for($index = 0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != ".")
{
echo '<tr><td width="33%" align="center" class="admin_td-even"><a href="' . $dirArray[$index] . '">' . $dirArray[$index] . '</a></td>';
echo '<td width="33%" align="center" class="admin_td-odd">';
echo strtoupper(substr($dirArray[$index], -3));
echo '</td>';
echo '<td width="33%" align="center" class="admin_td-even">';
echo filesize($dirArray[$index]);
echo '</td>';
echo '</tr>';
}
}
echo '</table>';
?>
一旦你看到你不想要的东西,就放置一个 continue
语句,该语句支持循环到 for 条件。
我看到两种方法:
- 您可以稍后启动一个索引:
而不是for($index = 0; $index < $indexCount; $index++) { ...}
,做
for($index = 1; $index < $indexCount; $index++) { ...}
- 您还可以添加条件:
例如:
for ($index = 0; $index < $indexCount; $index++) {
if ($dirArray[$index] == 'INDEX.PHP') continue;
// rest of the loop
}
但它们是改进代码的几种方法。与其使用 opendir()
和 readdir()
,不如像这样使用 scandir:
foreach (scandir('.') as $file) {
}
但看起来您想抓取一些媒体文件并显示它们。所以更好的解决方案是使用 glob() 函数,如下所示:
foreach (glob("*{.mp3,.mp4,.jpg,.png}", GLOB_BRACE) as $filename) {
echo "$filename size " . filesize($filename) . "'n";
}
循环是否将文件作为对象返回? 然后你可以添加一个 if 语句到文件名参数
for($index = 0; $index < $indexCount; $index++)
{
//skip first entry
if($index == 0) continue;
if (substr("$dirArray[$index]", 0, 1) != ".")
{
echo '<tr><td width="33%" align="center" class="admin_td-even"><a href="' . $dirArray[$index] . '">' . $dirArray[$index] . '</a></td>';
echo '<td width="33%" align="center" class="admin_td-odd">';
echo strtoupper(substr($dirArray[$index], -3));
echo '</td>';
echo '<td width="33%" align="center" class="admin_td-even">';
echo filesize($dirArray[$index]);
echo '</td>';
echo '</tr>';
}
}
只需通过将当前文件的名称与所需文件的名称进行比较来忽略所需的文件。例如,您可以在列表检索中执行此操作:
$myDirectory = opendir('.');
while( false!==($entryName = readdir($myDirectory)) )
{
if( strtolower($entryName)=='index.php' )continue;
$dirArray[] = $entryName;
}
closedir($myDirectory);
不要依赖索引(文件数),因为您的index.php
可能不是列表中的第一个。
for($index = 0; $index < $indexCount; $index++) {
if(index == 0) continue;
// other stuff
}