dougaodi8895 2013-07-18 07:48
浏览 34

使用PHP从目录中随机生成多个文件

I am building a website where people can go and upload images, gifs, and videos. On the home page, I want to list files at random from the upload directory.

<article class="item thumb" data-width="384">
    <h2><?php echo $file_title;?></h2>
    <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt=""></a>
</article>

<article class="item thumb" data-width="274">
    <h2><?php echo $file_title;?></h2>
    <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt=""></a>
</article>

And it does that for a total of five times. $randomImage is generated from the code:

<?php
   $imagesDir = 'uploads/';
   $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
   $randomImage = $images[array_rand($images)];
   $file_title = $randomImage;
?> 

I want to be able to add a feature to where as the user scrolls down, more and more of these articles containing images show up, each containing a random but not previously shown file. How can I display files at random without having to manually enter unique variables?

P.S. Right now I do not have any files stored in a database.

  • 写回答

1条回答 默认 最新

  • duanhuokuang5280 2013-07-18 09:29
    关注

    Remove randomly selected image from $images before you select another.

    loop for 5 images

    <?php
    // get all files
    
    $imagesDir = 'uploads/';
    $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    $imagesCount = count($images);
    
    for($i = 0 ; $i < $imagesCount ; $i++) {
    
        // select image 
    
        $randomIndex = array_rand($images); // select image index
    
        $file_title = $randomImage = $images[$randomIndex]; // use selected image
    
        unset($images[$randomIndex]); // remove selected image
        // print_r($images); // you can see what left in $images
    
        // show image
    
        ?>
        <article class="item thumb">
            <h2><?php echo $file_title;?></h2>
            <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt=""></a>
        </article>
        <?php
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错