我想知道从文件夹中拉出随机图像的“更好”方式。从文件夹中拉出随机图像
就像说,让PHP只是从文件夹中选择一个随机图像,而不是搜索和创建一个数组。
这里是我今天做
<?php
$extensions = array('jpg','jpeg');
$images_folder_path = ROOT.'/web/files/Header/';
$images = array();
srand((float) microtime() * 10000000);
if ($handle = opendir($images_folder_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$ext = strtolower(substr(strrchr($file, "."), 1));
if(in_array($ext, $extensions)){
$images[] = $file;
}
}
}
closedir($handle);
}
if(!empty($images)){
$header_image = $images[array_rand($images)];
} else {
$header_image = '';
}
?>
**您的答案很好,很简短!**但还有一个问题! 如果图像目录包含大量图像(1K),[scandir](http://php.net/manual/en/function.scandir.php)会将所有图像加载到数组中。 虽然你只需要一个图像。有没有办法改善你的答案?如果你可以用一个选项来包装它,以获得有限数量的图像。即'$ returned_images_count = 10;',我的意思是在[这个问题]中部分解释(https://stackoverflow.com/q/10642777/7735285)。 +'opendir'在分析过程中看起来更快。 – wpcoder 2017-10-30 19:32:59