从目录中随机选择两个(唯一的)图像

use*_*758 2 php random unique

我有这个代码运作良好:

function random_pic($dir = 'img')
{
    $files = glob($dir . '/*.png');
    $file = array_rand($files);             
}
Run Code Online (Sandbox Code Playgroud)

它从目录中抓取随机图像.我以后有这个:

<img src="<?php echo random_pic(); ?>"/>
<img src="<?php echo random_pic(); ?>"/>
Run Code Online (Sandbox Code Playgroud)

我能以任何方式制作它们,它们都不会显示相同的图片吗?

Fra*_*oMM 5

试试这个:

$indexes=array_rand($files,2);
$file1=$files[$indexes[0]];
$file2=$files[$indexes[1]];
Run Code Online (Sandbox Code Playgroud)

array_rand可以检索多个键,只需指定2作为第二个参数.在这种情况下,它返回am数组.

function random_pics($dir = 'img',$howMany=2) {
    $files = glob($dir . '/*.png');
    if($howMany==0) $howMany=count($files); // make 0 mean all files
    $indexes = array_rand($files,$howMany);
    $out=array();
    if(!is_array($indexes)) $indexes=array($indexes); // cover howMany==1
    foreach($indexes as $index) {
        $out[]=$files[$index];
    }
    return $out;
}

$theFiles=random_pics();


<?php echo $theFiles[0]; ?>
<?php echo $theFiles[1]; ?>
Run Code Online (Sandbox Code Playgroud)