2011-02-24 103 views
3

我正在加载一个完整的图像文件夹,创建一个jQuery图像库。PHP随机图像

当前有100张图片正在加载以创建图库。我已经加载了所有这些,没有问题。

我想要做的就是让图像加载,随机加载。

我该如何做到这一点?

我的代码是:提前

<?php 
      $folder = "images/"; 
      $handle = opendir($folder); 
      while(($file = readdir($handle)) !== false) {  
       if($file != "." && $file != "..") 
       {  
       echo ("<img src=\"".$folder.$file."\">"); 
       } 
} 
?> 

感谢。

回答

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."\">"); 
    } 

?> 
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. 
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."\">"); 
      } 
} 
?>