从文件夹 php 中选择随机不同图像


Select Random Distinct Images from a folder php

我想从一个包含多个图像的文件夹中随机选择四个图像。

我想显示的是一个表格(2x2),我可以在其中显示4个随机不同的图像。

有人可以告诉我如何从文件夹中选择随机不同的文件,以便我可以将它们的路径存储在变量中,然后可以使用这些变量在表中随机显示图像!

是否有任何特定的功能可以从文件夹中选择随机文件或类似的东西?

  1. 使用 glob() 从目录中获取所有文件。
  2. 使用 array_rand() 从数组中获取随机条目。
<?php


    function get_imagess($root) {
    $r = array();
    $r = array();
    $k = glob("$root/*");
    shuffle($k);
    foreach($k as $n) {
        if (is_dir($n)) {
            break;
            //$r = array_merge($r, get_imagesss($n));
            print_r("xxx");
        } else {
           $r[] = $n;
           //print_r($n + "yeah");     
        }
    }
    return $r;
}
    function get_images($root) {
    $r = array();
    $k = glob("$root/*");
    shuffle($k);
    $n = $k[0];
//    foreach($k as $n) {
        if (is_dir($n)) {
            $r = array_merge($r, get_imagess($n));
        } else {
           $r[] = $n;
        }
//    }
    return $r;
}

$files = get_images('.');
//print_r($files);
//break;


shuffle($files);
$true=true;
    $extList = array();
    $extList['gif'] = 'image/gif';
    $extList['jpg'] = 'image/jpeg';
    $extList['jpeg'] = 'image/jpeg';
    $extList['png'] = 'image/png';
        $ass=0;
while($true)
    {
        $ass=$ass+1;
        if($ass>100){$true=false;}
        $imageInfo = pathinfo($files[0]);
        if (isset( $extList[ strtolower( $imageInfo['extension'] ) ] )){
    $temp = substr($files[0], -5);  
    $temp = strtolower($temp);
    if( $temp == "p.jpg"){shuffle($files);}  // checking if jpg has a preview file
    else{  // no preview found
    $true=false;
    //print_r($temp);
    }}
    else
        {
        shuffle($files);
        //print_r('bad' + $temp);
        }
}
//print_r($files[0]);
echo '<HTML><meta HTTP-EQUIV="Refresh" CONTENT="5; URL=./ImageRotateMaybe.php"><img src="';
echo $files[0];
echo ' " width=100%>';
?>