dpb56083 2016-05-01 12:55
浏览 82
已采纳

PHP:如何用array_rand显示几个随机图像?

I'm using this script to display one random image from a folder with subfolders:

<?php
$imagesDir = glob('folders/pics/*', GLOB_ONLYDIR);
$randomfolder = $imagesDir[array_rand($imagesDir)];
$images = glob($randomfolder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo '<img src="'.$randomImage.'" class="image">'; 
?>

Everything works fine! But for now I want to show 5 images at the same time (for a caroussel-slider). I used the following code

$randomImage = $images[array_rand($images, 5)];

but it shows me this warning:

Warning: Illegal offset type […]

What am I doing wrong?

  • 写回答

3条回答 默认 最新

  • dongre6227 2016-05-01 12:59
    关注

    You are using array_rand() function wrong. It will return an array of keys, not a single number. What you could do is:

    $randomImageKeys = array_rand($images, 5);
    for ($randomImageKeys as $key) {
       echo '<img src="'.$images[$key].' class="image">';
    }
    

    But like this you risk an E_WARNING if your $images array contains less than 5 images - to avoid this, you could use the following:

    $max = (count($images) < 5) ? count($images) : 5;
    $randomImageKeys = array_rand($images, $max);
    for ($randomImageKeys as $key) {
       echo '<img src="'.$images[$key].' class="image">';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分