【问题标题】:Randomly selecting two (unique) images from a directory从目录中随机选择两个(唯一)图像
【发布时间】:2012-11-29 22:58:32
【问题描述】:

我有这个运行良好的代码:

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(); ?>"/>

有什么办法可以让它们不显示相同的图片?

【问题讨论】:

    标签: php random unique


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 不知道那个,但这是我解决这个问题的两个方法之一。
    【解决方案2】:

    你还记得最后一个吗?然后检查它是否被使用?如果是的话,买一个新的。

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

    在标记中。

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

    【讨论】:

      【解决方案3】:

      我认为您将按顺序调用 random_pic 函数,因此您可以返回选择的图片并将其作为参数提供给您第二次调用该函数。然后改变功能,不选择转发的图片。

      【讨论】:

        【解决方案4】:
        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));
        

        【讨论】:

          【解决方案5】:

          最简单的方法如下:

          <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/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-07-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多