如何在 PHP 中使用'opendir()”按字母顺序对目录列表进行排序?

Mary-Kate Olsen
发布: 2024-10-27 17:47:01
原创
184 人浏览过

How do I sort a directory listing alphabetically using `opendir()` in PHP?

在 PHP 中使用 opendir() 按字母顺序对目录列表进行排序

要在 PHP 中使用 opendir() 按字母顺序对目录列表进行排序,请按照以下步骤操作:

  1. 将文件收集到数组中:在排序之前,使用 $dirFiles = array(); 将所有文件读取到数组中,类似于:
<code class="php">$dirFiles = array();
while (false !== ($file = readdir($handle))) {
    $dirFiles[] = $file;
}</code>
登录后复制
  1. 对数组进行排序: 文件放入数组后,您可以使用 sort() 按字母顺序对它们进行排序:
<code class="php">sort($dirFiles);</code>
登录后复制
  1. 显示排序的列表:最后,迭代排序的 $dirFiles 数组并像以前一样显示图像和缩略图:
<code class="php">foreach($dirFiles as $file)
{
    echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\"  </a></li>\n";
}</code>
登录后复制

这是一个包含这些的修改后的脚本步骤:

<code class="php">... (unchanged code) ...

// Read files into an array
$dirFiles = array();
while (false !== ($file = readdir($handle))) {
    if ($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "index.php" &amp;&amp; $file != "Thumbnails") {
        $dirFiles[] = $file;
    }
}
closedir($handle);

// Sort the array
sort($dirFiles);

// Display the sorted listings
foreach($dirFiles as $file)
{
    echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\"  </a></li>\n";
}</code>
登录后复制

以上是如何在 PHP 中使用'opendir()”按字母顺序对目录列表进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!