2011-02-24 136 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."\">"); 
      } 
} 
?>