使用readdir()时输出输出

时间:2012-09-01 22:57:02

标签: php readdir

我对PHP很新,并且一直在使用PHP的readdir()来查看一个充满图像的文件夹,并根据该文件夹中有多少图像动态渲染它们。一切都很好,但我注意到的一件事是图像没有按照它们出现在我本地机器HD上的顺序显示。

所以我对任何知道PHP的人的问题是,有没有办法使用PHP来读取文件夹的内容并按顺序显示它们而不必重命名实际的文件名,例如01.jpg,02.jpg等等?

5 个答案:

答案 0 :(得分:1)

查看glob()函数,它按字母顺序返回按默认排序的文件:

$files = glob('/some/path/*.*');

奖金,您可以只过滤图像,并省略目录。

答案 1 :(得分:0)

readdir可能只是采用文件系统顺序。这在NTFS上是按字母顺序排列的,但在大多数Unix文件系统上看似随机。 documentation甚至可以说:»条目按文件系统存储的顺序返回。«

因此,您必须将列表存储在一个数组中,并根据您希望对它们进行排序的方式对其进行排序。

答案 2 :(得分:0)

php手册说:

string readdir ([ resource $dir_handle ] )
Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

意思是它们应该以相同的方式出现。

the manual中的更多信息。

答案 3 :(得分:0)

为什么不应用其中一个sort-functions of PHP

$files = readdir( $theFoldersPath );
sort( $files  );

答案 4 :(得分:0)

以下是我在回答问题时(连同发布人员的帮助)提出的问题。

<?php 

$dir = "low res";
$returnstr = "";

// The first part puts all the images into an array, which I can then sort using natsort()
$images = array();

if ($handle = opendir($dir)) {
    while ( false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != ".."){
            $images[] = $entry;
        }
    }
    closedir($handle);
}

natsort($images);
print_r($images);

$newArray = array_values($images);

// This bit then outputs all the images in the folder along with it's own name

foreach ($newArray as $key => $value) {
    // echo "$key - <strong>$value</strong> <br />"; 

    $returnstr .= '<div class="imgWrapper">';
    $returnstr .= '<div class="imgFrame"><img src="'. $dir . '/' . $value . '"/></div>';
    $returnstr .= '<div class="imgName">' . $value . '</div>';
    $returnstr .= '</div>';


}

echo $returnstr;
?>