PHP从目录中随机显示n张图像 [英] PHP display random n images from directory

查看:104
本文介绍了PHP从目录中随机显示n张图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件夹中随机显示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}
}?>

用法:
displayImgs(/ dir / temp /路径,20);

I want to display random n number of images from a folder. Currently i am using this script to display images

<?php
$dir = './images/gallery/';
foreach(glob($dir.'*.jpg') as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php } ?>

I want only 10 (or n number) images, that too randomly. How to do this?

解决方案

The 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 } 
} ?>

Usage: displayImgs("/dir/temp/path", 20);

这篇关于PHP从目录中随机显示n张图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆