我正在加载一个包含图像的文件夹,以创建一个jQuery图库。
目前正在加载100张图片来创建图库。我已经把所有这些都加载了而没有问题。
我想做的就是制作加载的图像,随机加载。
我如何实现这一目标?
我的代码是:
<?php
$folder = "images/";
$handle = opendir($folder);
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..")
{
echo ("<img src=\"".$folder.$file."\">");
}
}
?>
提前致谢。
答案 0 :(得分:8)
只需将所有图像路径存储在一个数组中,然后对数组进行随机混乱。然后回应元素
<?php
$folder = "images/";
$handle = opendir($folder);
$imageArr = array();
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..")
{
$imageArr[] = $file;
}
shuffle($imageArr); // this will randomly shuffle the image paths
foreach($imageArr as $img) // now echo the image tags
{
echo ("<img src=\"".$folder.$img."\">");
}
}
?>
答案 1 :(得分:6)
遍历目录并将图像文件名存储到数组中,并从数组中随机选择路径名。
一个基本的例子:
$dir = new DirectoryIterator($path_to_images);
$files = array();
foreach($dir as $file) {
if (!$fileinfo->isDot()) {
$files[] = $file->getPathname();
}
}//$files now stores the paths to the images.
答案 2 :(得分:4)
您可以尝试这样的事情:
<?php
$folder = "images/";
$handle = opendir($folder);
$picturesPathArray;
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..")
$picturesPathArray[] = $folder.$file;
}
shuffle($picturesPathArray);
foreach($picturesPathArray as $path) {
echo ("<img src=\"".$path."\">");
}
?>