问题描述
我正在尝试为一个内容块(在一个网页上)分配一个随机生成的数字,该数字基于今天的日期(无论是什么日期)和固定的数字之间。由于某些原因,输出的数字种类存在巨大差异。例如,当我在本地测试我的代码时,生成的数字对我来说已经足够了(正数),但是在实际的实时服务器上,它们通常是相反的并且是负数。
I am trying to assign a block of content (on a webpage) a randomly generated number that is based between todays date (whatever that will be) and a fixed number. For some reason there is dramatic difference in the sorts of numbers being outputted. For example when I test my code locally the numbers generated are good enough for me (in the positive) but when on an actual live server they are generally the opposite and are negative numbers.
这是我的班轮:
<?php $today=date('YmdHi'); echo rand(201203140906, $today); ?>
基本上'201203140906'是年,月,日,小时。
Basically '201203140906' is the Year, Month, Day, Hour.
这是好事还是坏事?有更好的方法吗?
Is this good or bad? Are there better ways to do this?
推荐答案
在32位系统上,可以保存在INT中的最大值是2147483647。
On a 32-bit system, the largest value that can be held in an INT is 2147483647.
如果您的本地计算机是64位并且服务器是32位,它们会有不同的大小限制。服务器将无法处理与201203140906一样大的整数。
If your local machine is 64 bit and your server is 32 bit, they will have different size limits. The server will not be able to handle an integer as large as 201203140906.
您可能能够随机生成一个较小的数字,然后将其添加到201203140906。
You may be able to randomly generate a smaller number and then add that to 201203140906.
例如:
$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('2012-03-14 09:06:00'));
$range = $today - $startDate;
$rand = rand(0, $range);
echo "$rand and " . ($startDate + $rand);
或者您可以执行以下操作以生成最近十天的随机日期:
OR you can do this to generate a random date in the last ten days:
$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('-10 days'));
$range = $today - $startDate;
$rand = rand(0, $range);
echo "$rand and " . ($startDate + $rand);
这篇关于PHP使用今天的日期生成一个随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!