使用 php 的随机图像集

Random set of images using php

我有这段代码,我一直用它来 select 一张随机图片。现在我需要 select 四张随机图片。

我已经尝试修改代码并且它确实有效,但我想不出一种方法来防止相同的图像出现两次。我对 php 的了解充其量只是基础知识。

任何人都可以解释一下吗?

谢谢

我的代码

<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/_/images/banners/';

function getImagesFromDir($path) {
    $images = array();
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {

            if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}

function getRandomFromArray($ar) {
    mt_srand( (double)microtime() * 1000000 );
    $num = array_rand($ar);
    return $ar[$num];
}

$imgList = getImagesFromDir($root . $path);

$imgA = getRandomFromArray($imgList);
$imgB = getRandomFromArray($imgList);
$imgC = getRandomFromArray($imgList);
$imgD = getRandomFromArray($imgList);
?> 

<img src="<?php echo $path . $imgA ?>" alt="<?php echo ucfirst(preg_replace('/\.[^.\s]{3,4}$/', '', $imgA)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgB ?>" alt="<?php echo ucfirst(preg_replace('/\.[^.\s]{3,4}$/', '', $imgB)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgC ?>" alt="<?php echo ucfirst(preg_replace('/\.[^.\s]{3,4}$/', '', $imgC)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgD ?>" alt="<?php echo ucfirst(preg_replace('/\.[^.\s]{3,4}$/', '', $imgD)) . ' Logo'; ?>">

使用array_rand()获取所需数量的随机密钥列表,而不仅仅是一个。第二个参数指定应返回多少个键:

<?php

$randomKeys = array_rand($imgList, 4);

foreach($randomKeys as $key) {
    echo '<img src="' . $path . $imgList[$key] . '" alt="' . ucfirst(preg_replace('/\.[^.\s]{3,4}$/', '', $imgList[$key])) . ' Logo">';
}

这应该适合你:

这里我只是从 glob(). After this I filter the array with array_filter() and only grab the files which matches to the array: ["gif", "jpg", "png"]. I do this with a simple in_array() check where I get the extension of the file with pathinfo() and take it in lowercase with strtolower().

目录中抓取所有文件

现在要获取随机图像,我只是 shuffle() the array and take X images from the array start with array_silce()

最后我只是简单地打印所有图像。

<?php

    $root = $_SERVER['DOCUMENT_ROOT'];
    $path = '/_/images/banners/';
    $random = 4;

    $images = array_filter(glob($root . $path . "*.*"), function($v){
        return in_array(strtolower(pathinfo($v, PATHINFO_EXTENSION)), ["gif", "jpg", "png"]);
    });

    shuffle($images);
    $randomImages = array_slice($images, 0, $random);

    foreach($randomImages as $v)
        echo "<img src='" . $v . "' alt='" . ucfirst(pathinfo($v, PATHINFO_FILENAME)) . " Logo'>";

?>