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

时间:2012-11-29 22:58:33

标签: php random unique

我有这个代码运作良好:

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

它从目录中抓取随机图像。我稍后会这样:

<img src="<?php echo random_pic(); ?>"/>
<img src="<?php echo random_pic(); ?>"/>

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

5 个答案:

答案 0 :(得分:5)

试试这个:

$indexes=array_rand($files,2);
$file1=$files[$indexes[0]];
$file2=$files[$indexes[1]];

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]; ?>

答案 1 :(得分:3)

你能记得最后一个。然后检查它是否被使用?如果是,请换一个新的。

$one = random_pic();
$two = random_pic();
while($one == $two){
$two = random_pic();
}

并在标记中。

<img src="<?php echo $one; ?>"/>
<img src="<?php echo $two; ?>"/>

答案 2 :(得分:0)

我认为你会按顺序调用random_pic函数,这样你就可以返回所选择的pic并将它作为参数提供给你的第二次函数调用。然后以这种方式更改功能,即不选择转发的图片。

答案 3 :(得分:0)

function random_pic($dir_only_imgs, $num) {

    shuffle($dir_only_imgs);
    $imgs = array();
    for ($i = 0; $i < $num; $i++) {
        $imgs[] = $dir[$i];
    }
    return $num == 1 ? $imgs[0] : $imgs;
}

$dir = "img"
$dir_only_imgs = glob($dir . '/*.png');

print_r(random_pic($dir_only_imgs, 2));

答案 4 :(得分:0)

最简单的方式如下:

<img src="https://www.example.com/images/image-<?php echo rand(1,7); ?>.jpg">

为了让它发挥作用,你需要为你的图像命名:image-1.jpg,image-2.jpg,image-3.jpg ,,, image-7.jpg,

当页面加载时,PHP rand()将回显一个随机数(在本例中为1到7之间的数字),完成URL并显示相应的图像。 资料来源:https://jonbellah.com/load-random-images-with-php/