php从目录中生成随机图像
我必须从目录中生成随机图像.我知道哪个很简单,
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?
谢谢.
推荐答案
array_rand 的一个替代方案是 shuffle:
One alternative to array_rand is shuffle:
$dire="images/";
$images = glob($dire. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
shuffle($images);
然后显示下一个随机图像:
And then to display the next random image:
$randomImage=array_pop($images);
当数组为空时,您再次调用初始化代码.所以把它放在一起:
When the array is empty you call the initialization code again. So putting it together:
$images=array() //Initialize once at top of script
$dire="images/";
...
if(count($images)==0){
$images = glob($dire. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
shuffle($images);
}
$randomImage=array_pop($images);
(我故意重复 glob() 以便在第二次迭代时发现任何新图像.)
(I deliberately repeated the glob() so that any new images get discovered on the second iteration.)
附言我假设您明白,默认情况下,PHP 是无状态的.如果这应该在每次访问页面时为每个用户提供不同的图像(例如旋转横幅广告),那么代码几乎相同,但将 $images
数组移动到 $_SESSION
.
P.S. I'm assuming you understand that, by default, PHP is stateless. If this is supposed to give each user a different image each time they visit a page (e.g. a rotating banner ad), then the code is almost the same, but move the $images
array into $_SESSION
.
相关文章