Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

php generate random image from a directory

I have to generate random image from a directory. I know which is simple like,

   $dire="images/";
   $images = glob($dire. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
   $randomImage = $images[array_rand($images)];
   <input type="image" src="<?=$randomImage;?>" alt="<?=$randomImage;?>" />

But I have to make sure that each image from that directory picked at least one time before generating second time randomly. The above code only will display only any random image.

My thought is, I have to store the random image in an array and check the array every time with newly created random image. If the new random image is not in that array, I need to display that image,else I have to find another image.

I created the below code with above thought.

  $allimgs=array();
  $dire="images/";
  $images = glob($dire. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
  $randomImage = $images[array_rand($images)];

   if(!in_array($randomImage,$allimgs))
   {
     $allimgs[]=$randomImage;
     <input type="image" src="<?=$randomImage;?>" alt="<?=$randomImage;?>" />
   }

But I am still stuck with this code. Anyone please help to improve this code? or any other idea?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One solution might be to do this:

<?
// initialize $images
shuffle($images);
$randomImage = array_pop($images);
?>
<input type="image" src="<?=$randomImage;?>" alt="<?=$randomImage;?>" />

This will guarantee that you use each image only once, in a random order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...