我向用户显示了一个随机数,并希望将该数保存到文本文件中。我的问题是显示的号码和保存的号码是不同的。我假设这是因为它只是生成两次随机数,而不是将第一个数(显示给用户的那个)写入文件。
<?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,依此类推。
<?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部分,并相应地更改最大值。
提供了一个完整的视图,我计划给出一个更好的背景,看看这是不是最好的方法。提前谢谢。
发布于 2021-06-25 19:33:41
问题来了,因为你调用了两次rand函数。你的逻辑在这里有点错误。要得到与txt文件相同的结果,您需要调用rand一次并将其保存到一个变量中,然后将该变量写入txt文件并将相同的变量回显给用户。
http://sandbox.onlinephpfunctions.com/code/6da31516233da56d852865847bde187443839816
https://stackoverflow.com/questions/68129984
复制相似问题