【发布时间】:2018-04-18 15:28:51
【问题描述】:
这是我的数组 基本上现在我有一个包含 100,000 张图像的目录。都是不同的名称,例如 d2jd29df.png fj329f.png 等。我希望它在网页上按字母顺序列出它们。有人可以在正确的方向上推动我吗?
【问题讨论】:
-
到目前为止您尝试过什么?发布您的一些代码,以便我们提供帮助
-
请把代码添加为代码,而不是没有人会点击的图片:)
这是我的数组 基本上现在我有一个包含 100,000 张图像的目录。都是不同的名称,例如 d2jd29df.png fj329f.png 等。我希望它在网页上按字母顺序列出它们。有人可以在正确的方向上推动我吗?
【问题讨论】:
您需要将整个目录读入一个数组,然后按字母顺序自然地(即人类的方式)对数组进行排序。最后,迭代每个文件并回显每个文件的文件名。
<?php
$files = array();
$dir = '/path/to/images';
$handle = opendir($dir);
if ($handle) {
while (false !== ($file = readdir($handle))) {
if ($file !== '.' && $file !== '..') {
$files[] = $file;
}
}
closedir($handle);
}
sort($files, SORT_NATURAL);
foreach ($files as $file) {
echo $file.'<br />';
}
【讨论】:
试试这个:
<?php
$dir = "path/to/image";
$images = glob("$dir/*.*");
$items = [];
foreach ($images as $image) {
$items[] = basename($image);
}
sort($items, SORT_STRING);
foreach ($items as $item) {
echo $item . '<br>';
}
将 $dir 的值更改为包含图像的目录。
【讨论】:
最简单的方法是使用scandir():
$contents = array_diff(scandir('/path/to/my/images/folder'), array('.', '..'));
// If you need to apply a custom sorting algorithm then try using
// natsort(), natcasesort(), usort(), or uasort() on $contents
// before looping through it.
//
// http://php.net/manual/en/array.sorting.php
foreach($contents as $item)
{
echo $item;
}
另外,您不妨查看scandir() 的sorting_order 参数。
【讨论】: