0

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

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

4

5 回答 5

1

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

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

奖励,您可以只过滤图像,而忽略目录。

于 2012-09-01T23:14:26.690 回答
0

readdir可能只需要文件系统顺序。在 NTFS 上按字母顺序排列,但在大多数 Unix 文件系统上似乎是随机的。文档甚至说了这么多:»条目按文件系统存储的顺序返回。«

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

于 2012-09-01T23:03:26.327 回答
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.

这意味着它们应该以相同的方式出现。

更多信息可在手册中找到。

于 2012-09-01T23:03:34.607 回答
0

为什么不应用PHP 的排序功能之一

$files = readdir( $theFoldersPath );
sort( $files  );
于 2012-09-01T23:07:14.517 回答
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;
?>
于 2012-09-03T16:11:15.580 回答