首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将相同的随机数写入文件,并基于随机选择显示DIV

将相同的随机数写入文件,并基于随机选择显示DIV
EN

Stack Overflow用户
提问于 2021-06-25 19:07:44
回答 1查看 25关注 0票数 0

我向用户显示了一个随机数,并希望将该数保存到文本文件中。我的问题是显示的号码和保存的号码是不同的。我假设这是因为它只是生成两次随机数,而不是将第一个数(显示给用户的那个)写入文件。

代码语言:javascript
运行
复制
<?php
  $min=1;
  $max=100;
  echo rand($min,$max);
  $file = fopen("./randomnumber.txt","a+ \n");
   fwrite($file,$min,$max);
   fclose($file);
?>

我希望显示给用户的数字实际上与写入文件的数字相同。我想要显示一个相应的图像,所以如果数字是1,它只回显图像1的转义html,如果是2,它就是2,依此类推。

代码语言:javascript
运行
复制
<?php
  $min=1;
  $max=100;
  echo rand($min,$max);
  $file = fopen("./randomnumber.txt","a+ \n");
   fwrite($file,$min,$max);
   fclose($file);

  if (rand === '1') {
      echo "
            <div class='image-1'>
                <p>Image 1 Goes Here if 1 is the random number</p>
            </div>";
  }
  
else if (rand === '2') {
      echo "
            <div class='image-2'>
                <p>Image 2 Goes Here if 2 is the random number</p>
            </div>";
  }
  
 else if (rand === '3') {
      echo "
            <div class='image-3'>
                <p>Image 3 Goes Here if 3 is the random number</p>
            </div>";
  }
   
 else if (rand === '4') {
      echo "
            <div class='image-4'>
                <p>Image 4 Goes Here if 4 is the random number</p>
            </div>";
  }
  
 else if (rand === '5') {
      echo "
            <div class='image-5'>
                <p>Image 5 Goes Here if 5 is the random number</p>
            </div>";
  }
  
// And so on. I need to be able to add new sections for every new image.
// I don't want the full code visible. I only want the DIV of the random selection pushed to the page so it doesn't need to load potentially hundreds of invisible images.
   
   
?>

这个想法是生成随机数并将数字保存到文件中,但除了显示数字以便用户必须自己搜索之外,我希望根据随机生成的数字向用户显示随机DIV,而不是加载每个推送到源代码的DIV,因为这可能意味着需要加载数百张图像,因为我会为每个图像添加一个新的html部分,并相应地更改最大值。

提供了一个完整的视图,我计划给出一个更好的背景,看看这是不是最好的方法。提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-06-25 19:33:41

问题来了,因为你调用了两次rand函数。你的逻辑在这里有点错误。要得到与txt文件相同的结果,您需要调用rand一次并将其保存到一个变量中,然后将该变量写入txt文件并将相同的变量回显给用户。

http://sandbox.onlinephpfunctions.com/code/6da31516233da56d852865847bde187443839816

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68129984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档