php - 在 php 中使用 opendir() 按字母顺序排序和显示目录列表

标签 php sorting directory

这里是 php noob - 我拼凑了这个脚本来显示带有 opendir 的文件夹中的图像列表,但我不知道如何(或在哪里)按字母顺序对数组进行排序

<?php

// opens images folder
if ($handle = opendir('Images')) {
while (false !== ($file = readdir($handle))) {

// strips files extensions  
$crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

$newstring = str_replace($crap, " ", $file );   

//asort($file, SORT_NUMERIC); - doesnt work :(

// hides folders, writes out ul of images and thumbnails from two folders

    if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
    echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\"  </a></li>\n";}
}
closedir($handle);
}

?>

任何建议或指示将不胜感激!

最佳答案

您需要先将文件读入数组,然后才能对它们进行排序。这个怎么样?

<?php
$dirFiles = array();
// opens images folder
if ($handle = opendir('Images')) {
    while (false !== ($file = readdir($handle))) {

        // strips files extensions      
        $crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

        $newstring = str_replace($crap, " ", $file );   

        //asort($file, SORT_NUMERIC); - doesnt work :(

        // hides folders, writes out ul of images and thumbnails from two folders

        if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
            $dirFiles[] = $file;
        }
    }
    closedir($handle);
}

sort($dirFiles);
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";
}

?>

编辑:这与您的要求无关,但您可以使用 pathinfo() 对文件扩展名进行更通用的处理。功能也。那时您不需要硬编码的扩展数组,您可以删除任何扩展。

关于php - 在 php 中使用 opendir() 按字母顺序排序和显示目录列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/884974/

相关文章:

java - 为什么这个循环排序实现有一个错误?

c - 按 qsort 排序后缀

directory - 从 gradle 中的构建目录运行脚本

php - 使用 PHP 更新 XML 节点

用于批量插入查询的php绑定(bind)动态变量数

PHP:htmlentities 不使用变量

arrays - 按值对 map 排序,然后将其放入GO中的另一张 map 中

c++ - 使用 C++ 和 Boost 创建目录时出错

c# - 在 WPF 应用程序中本地存储数据文件的文件夹

php - SQL 查询返回空值?