我对 PHP 相当陌生,并且一直在使用 PHP 的 readdir() 来查看一个充满图像的文件夹,并根据该文件夹中有多少图像动态地呈现它们。一切都很好,但我注意到的一件事是图像没有按照它们出现在我的本地机器 HD 上的顺序显示。
所以我对任何知道 PHP 的人的问题是,有没有办法使用 PHP 来读取文件夹的内容并按顺序显示它们,而不必重命名实际的文件名,例如 01.jpg、02.jpg 等?
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;
?>