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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/884974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:12:38  来源:igfitidea点击:

Sort and display directory list alphabetically using opendir() in php

phpsortingdirectory

提问by felixthehat

php noob here - I've cobbled together this script to display a list of images from a folder with opendir, but I can't work out how (or where) to sort the array alphabetically

php noob here - 我已经拼凑了这个脚本来显示来自 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);
}

?>

Any advice or pointers would be much appreciated!

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

回答by zombat

You need to read your files into an array first before you can sort them. How about this?

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

<?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";
}

?>

Edit: This isn't related to what you're asking, but you could get a more generic handling of file extensions with the pathinfo()function too. You wouldn't need a hard-coded array of extensions then, you could remove any extension.

编辑:这与您要问的内容无关,但是您也可以使用pathinfo()函数对文件扩展名进行更通用的处理。你不需要一个硬编码的扩展数组,你可以删除任何扩展。

回答by Amal Murali

Using opendir()

使用 opendir()

opendir()does not allow the list to be sorted. You'll have to perform the sorting manually. For this, add all the filenames to an array first and sort them with sort():

opendir()不允许对列表进行排序。您必须手动执行排序。为此,首先将所有文件名添加到数组中并使用sort()以下命令对其进行排序:

$path = "/path/to/file";

if ($handle = opendir($path)) {
    $files = array();
    while ($files[] = readdir($dir));
    sort($files);
    closedir($handle);
}

And thenlist them using foreach:

随后用一一列举foreach

$blacklist = array('.','..','somedir','somefile.php');

foreach ($files as $file) {
    if (!in_array($file, $blacklist)) {
        echo "<li>$file</a>\n <ul class=\"sub\">";
    }
}

Using scandir()

使用 scandir()

This is a lot easier with scandir(). It performs the sorting for you by default. The same functionality can be achieved with the following code:

使用scandir(). 它默认为您执行排序。可以使用以下代码实现相同的功能:

$path = "/path/to/file";
$blacklist = array('somedir','somefile.php');

// get everything except hidden files
$files = preg_grep('/^([^.])/', scandir($path)); 

foreach ($files as $file) {
    if (!in_array($file, $blacklist)) {
        echo "<li>$file</a>\n <ul class=\"sub\">";
    }
}

Using DirectoryIterator(preferred)

使用DirectoryIterator(首选)

$path = "/path/to/file";
$blacklist = array('somedir','somefile.php');

foreach (new DirectoryIterator($path) as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $file =  $path.$fileInfo->getFilename();
    echo "<li>$file</a>\n <ul class=\"sub\">";
}

回答by namit

This is the way I would do it

这是我会做的方式

if(!($dp = opendir($def_dir))) die ("Cannot open Directory.");
while($file = readdir($dp))
{
    if($file != '.')
    {
        $uts=filemtime($file).md5($file);  
        $fole_array[$uts] .= $file;
    }
}
closedir($dp);
krsort($fole_array);

foreach ($fole_array as $key => $dir_name) {
  #echo "Key: $key; Value: $dir_name<br />\n";
}

回答by Jason

Note: Move this into the foreach loop so that the newstring variable gets renamed correctly.

注意:将其移动到 foreach 循环中,以便正确重命名 newstring 变量。

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

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

回答by Jason

$directory = scandir('Images');