开发者

PHP to randomise image

I'm loading a folder full of images in, to create a jQuery Image Gallery.

There are currently 100 images being loaded in to create the gallery. I've got all that to load without issue.

All I want to do is make the image(s) that are loaded, load in randomly.

How do I achieve this?

My code is :

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

Thanks in advance.


Just store all the image paths in an array and do a random shuffle of the array. And then echo the elements

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


Traverse the directory and store the image file names into an array and randomly select path names from the array.

A basic example:

$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. 


You can try something like this:

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

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜