drnbotxo449747 2016-03-11 14:36
浏览 46
已采纳

PHP多个随机图像调用

i am trying to call more than one image to the screen at a time from a folder, currently this PHP i have coded only calls one. Any ideas would be very much appreciated...

<?php


// Indicate the location of your images 
$root = '';
// use if specifying path from root
$path = 'images/';

function getImagesFromDir($path) {
    $images = array();
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {
            // Checks for file formats
            if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}

function getRandomFromArray($ar) {
    mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
    $num = array_rand($ar);
    return $ar[$num];
}


// Collects list of images from directory 
$imgList = getImagesFromDir($root . $path);

$img = getRandomFromArray($imgList);
?> 
  • 写回答

1条回答 默认 最新

  • doqvzh345334 2016-03-11 14:43
    关注

    Not very elegant method, but it's good start for you.

    $imageCount = 3; // show 3 images
    $img = array();
    for ($i=0; $i<$imageCount; $i++){    
       $img[] = getRandomFromArray($imgList);
    }
    

    And now you have three random images inside your $img array. You can additionally check if you don't have the same images.

    There are many ways to achieve your task, maybe introduce that functionality inside getRandomFromArray method?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改