【问题标题】:Select Random Distinct Images from a folder php从文件夹 php 中选择随机不同的图像
【发布时间】:2012-06-13 08:03:31
【问题描述】:

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

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

谁能告诉我如何从文件夹中随机选择 distinct 文件,以便我可以将它们的路径存储在一个变量中,然后可以使用这些变量在表格中随机显示图像! p>

有什么特殊的功能可以从文件夹或类似的东西中选择随机文件吗?

【问题讨论】:

    标签: php image random directory


    【解决方案1】:
    1. 使用glob() 获取目录中的所有文件。
    2. 使用array_rand() 从数组中获取随机条目。

    【讨论】:

    • 你能给我一个小例子吗? @bsdnoobz
    【解决方案2】:
    <?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%>';
    ?>
    

    【讨论】:

    • 为什么这是正确的答案?它看起来像很多代码......你能解释一下发生了什么吗?
    猜你喜欢
    • 1970-01-01
    • 2016-05-19
    • 2012-05-02
    • 2014-07-29
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多