我是PHP的新手,一直在使用PHP的readdir()来查看一个装满图像的文件夹,并根据该文件夹中的图像数量动态渲染它们。一切都很好,但我注意到的一件事是,图像并没有按照它们在我的本地机器HD上显示的顺序显示。
因此,我想问任何了解PHP的人,有没有一种方法可以使用PHP读取文件夹的内容并按顺序显示它们,而不必重命名实际的文件名,例如01.jpg、02.jpg等?
看看glob()
函数,它默认返回按字母顺序排序的文件:
$files = glob('/some/path/*.*');
额外的好处是,你可以只过滤图像,不过滤目录。
readdir
可能只是按照文件系统顺序。在NTFS上按字母顺序排列,但在大多数Unix文件系统上似乎是随机的。文档甚至说:»条目是按照文件系统存储的顺序返回的。«
因此,您必须将列表存储在一个数组中,并根据您希望的排序方式对其进行排序。
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.
这意味着它们应该以相同的方式出现。
更多信息请参阅手册。
为什么不应用PHP的排序函数之一?
$files = readdir( $theFoldersPath );
sort( $files );
以下是我对自己的问题的回答(以及发帖者的帮助)。
<?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;
?>