可以优化此循环浏览文件夹中照片的代码吗?
我已经编写了这段代码,现在已经 2 年没有使用 PHP 来循环遍历照片文件夹并按字母顺序将它们写入页面。 这是一个相当简单的请求,但我花了 15 分钟的时间来写。
if ($handle = opendir('photos')) {
$count = 0;
$list[] = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[$count] = $file;
$count ++;
}
}
closedir($handle);
asort($list);
$sorted_list = array();
$sorted_list = array_values($list);
foreach ($sorted_list as $i => $value) {
echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n";
}
}
我是不是完全写错了? 有什么方法可以改进代码吗? 很高兴收到任何建设性的反馈。
I have written this code having not used PHP for 2 years now to loop through a folder of photos and write them to the page in alphabetical order. It is a fairly simple request but it took me the best part of 15 minutes to write.
if ($handle = opendir('photos')) {
$count = 0;
$list[] = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[$count] = $file;
$count ++;
}
}
closedir($handle);
asort($list);
$sorted_list = array();
$sorted_list = array_values($list);
foreach ($sorted_list as $i => $value) {
echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n";
}
}
Have I written it totally the wrong way? Are there ways I can improve the code? Any constructive feedback gladly received.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以利用 scandir() 函数,该函数将处理读取目录并对结果进行排序。
为了便于阅读,我对其进行了一些编辑。
You could take advantage of the scandir() function, which will handle reading the directory as well as sorting the results.
I edited it a bit for readability.
试试这个:
http://us.php.net/manual/en/function .glob.php
Try this:
http://us.php.net/manual/en/function.glob.php
您不需要
$count
。 这将为您提供相同的结果将排序和显示替换为:
You don't need the
$count
. This will give you the same resultReplace sorting and displaying with just:
您可以替换
为
然后您不需要调用 array_values(),因为数组键不按数字顺序并不重要。
You can replace
with
Then you don't need to call array_values(), because it doesn't matter that the array keys aren't in numeric order.
更简单的方法是使用 scandir 函数:
祝你好运!
A simplier way is using the scandir function:
good luck!