douweng3383 2011-11-26 19:56
浏览 58
已采纳

PHP随机图像集

I'm using a php script to randomly show images. I've duplicated this script three times because I wanted to show three random images at once - I'm unsure of how to change the php code to show 3 images.

The problem is, I don't want to run into the chance of all three scripts showing the same images at once. Is there something that I could add to this code to make sure that each image displayed is always different?

<?php 
$random = "random.txt"; 
$fp = file($random); 
srand((double)microtime()*1000000); 
$rl = $fp[array_rand($fp)]; 
echo $rl; 
?>

the html:

 <?php include("rotate.php"); ?>
 <?php include("rotate.php"); ?>
 <?php include("rotate.php"); ?>

*the random.txt just has a list of filenames with links.

  • 写回答

4条回答 默认 最新

  • duanpiao6679 2011-11-26 20:09
    关注

    You can use array_rand() to select more than one random key at a time, like this:

    $random = "random.txt";
    $fp = file($random);
    shuffle($fp);
    // You don't need this. The array_rand() function
    // is automatically seeded as of 4.2.0
    // srand((double)microtime()*1000000);
    $keys = array_rand($fp, 3);
    for ($i = 0; $i < 3; $i++):
        $rl = $fp[$keys[$i]]; 
        echo $rl;
    endfor;
    

    This would eliminate the need for including the file multiple times. It can all be done at once.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?