PHP从目录中随机显示n张图像 [英] PHP display random n images from directory
问题描述
我想从文件夹中随机显示n张图片。目前,我正在使用此脚本来显示图像
<?php
$ dir ='./images/gallery /';
foreach(glob($ dir。'*。jpg')as $ file){?>
< div class =item>< img src =<?php = $ file;?>>< / div>
<?php}?>
我只需要10个(或n个)图像,这个图像太随机了。如何做到这一点?
shuffle()
给定数组的元素按随机顺序排列:
<?php
$ dir ='./images /画廊/';
function displayImgs($ dir,$ n = 10){
$ files = glob($ dir。'*。jpg');
shuffle($ files);
$ files = array_slice($ files,0,$ n);
foreach($ files为$ file){?>
< div class =item>< img src =<?php = $ file;?>>< / div>
<?php}
}?>
用法: I want to display random n number of images from a folder. Currently i am using this script to display images I want only 10 (or n number) images, that too randomly. How to do this? The Usage:
displayImgs("/dir/temp/path", 20); 这篇关于PHP从目录中随机显示n张图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
displayImgs(/ dir / temp /路径,20); <?php
$dir = './images/gallery/';
foreach(glob($dir.'*.jpg') as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php } ?>
shuffle()
method will put the elements of a given array in a random order:<?php
$dir = './images/gallery/';
function displayImgs($dir, $n=10){
$files = glob($dir.'*.jpg');
shuffle($files);
$files = array_slice($files, 0, $n);
foreach($files as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php }
} ?>