[英]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/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 }
} ?>
用法: displayImgs(“ / dir / temp / path”,20);
好吧,這可能有點過分,但是您也可以使用目錄迭代器和一些隨機性來實現此目的。 我從該答案中使用了隨機數生成函數的修改版本。
確保您提供給函數的路徑相對於腳本所在的目錄, 並以斜杠開頭。 如果您碰巧從文件層次結構的不同位置調用此腳本,則__DIR__
常量將不會更改。
<?php
function randomImages($path,$n) {
$dir = new DirectoryIterator(__DIR__. $path);
// we need to know how many images we can range on
// but we do not want the two special files . and ..
$count = iterator_count($dir) - 2;
// slightly modified function to create an array containing n random position
// within our range
$positionsArray = UniqueRandomNumbersWithinRange(0,$count-1,$n);
$i = 0;
foreach ($dir as $file) {
// those super files seldom make good images
if ($file->getFilename() === '.' || $file->getFilename() === '..') continue;
if (isset($positionsArray[$i])) echo '<div class="item"><img src="'.$file->getPathname().'"></div>';
$i++;
// change the count after the check of the filename,
// because otherwise you might overflow
}
}
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_flip(array_slice($numbers, 0, $quantity));
}
使用稱為rand()
內置隨機函數:
<?php
$dir = './images/gallery/';
for($i=0;$i<=10;$i++) {
echo '<div class="item"><img src="'.$dir.rand(1,10).'.jpg"></div>';
}
?>
讓我們首先創建一個數組並將一些隨機數推入其中。 按照您的假設, $n
等於10
。
$n = 10;
$arr = array();
for($i = 1; $i <= $n; $i++){
/* Where $n is the limit */
$rand = rand($n);
array_push($arr, $rand);
}
所以現在我們有了一個包含隨機數字的數組,現在我們必須通過遍歷該數組來回顯圖像:
foreach($arr as $image){
$intToStr = (string) $image;
foreach(glob($dir. $intToStr . '.jpg') as $file){
echo "<div class='item'>$file</div>";
}
}
這會回顯您的圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.