PHP从目录中随机显示n张图像

编程入门 行业动态 更新时间:2024-10-24 00:24:30
本文介绍了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张图像

本文发布于:2023-11-02 08:24:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   目录中   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!