簡體   English   中英

如何每x個月產生一個隨機數?

[英]How can I generate a random number every x amount of months?

從數字9開始並使用php,我希望能夠從那里開始計數,並以1的增量回顯下一個數字。因此,數字9,然后在1個月后,數字將變為10,然后是另一個第11個月,然后是12個,依此類推,沒有最大數量/停止點。

我該怎么做? 到目前為止,我有下面的代碼。

$number = 9;
$output = $number + 1;

echo $output;

有沒有辦法將其設置為每月增加一次?

根據您的問題,我會說:

$number = 9;
$output = date('n') + $number;
echo $output;

但這取決於您要完成的工作。 您還可以使用模將數字包裝在date()周圍。

但是,這不是隨機的。 如果您想按照主題建議每月創建一個隨機數,請使用該月份作為隨機種子。

srand(date('n'));
$number = rand();

一種非常低效的方式是

<?php
function increm($duration){
  while ($i<$duration) {
    $i++;
  }
  return true;
}
$number = 9;
$start = time();
$i = 0;
while (1){
  increm(3600*24*30);
  $i++;
  // Do your code
}
?>

該腳本必須連續運行幾個月。

更好的方法是

<?php
$number = 9;
if(!file_exists('date.txt')){
   $date=date('n');
   file_put_contents( (string)time());
   $date = 0;
}
else{
  $date= file_get_contents('date.txt');
  $date= date()-(int)$date;
  $date= floor($date/(24*3600*30));
}
// do whatever you may
?>

但是,只要存儲了第一個開放日期,此腳本都會增加它的數量。 將永遠有效(直到UNIX可以打上時間戳)。

您可以使用PHP date()函數來執行此操作。 如果您不依賴於月份中的某天,這就是這樣做的一個示例,但是可以添加日期功能,並且應該很容易地退出。

$startNumber = 9;

$startYear = 2015;
$startMonth = 9;

$currentYear = intval( date( "Y" ) );
$currentMonth = intval( date( "n" ) );

$monthsToAdd = ( ( $currentYear - $startYear ) * 12 )
             + ( $currentMonth - $startMonth );

echo $startNumber + $monthsToAdd;

為此,您必須將數字存儲在數據庫中,與當前的unix時間戳進行比較,並在達到新的月份時對其進行更新。

2個數據庫列: count_month int(10)next_month int(10) ,其中next_month將包含下個月第一天的Unix時間戳。 您可以使用cronjobs或在生產環境中運行它。

<?php
$now = strtotime("now");
$next_month = strtotime("first day of next month");

if ($query = $dbconnect->prepare("SELECT next_month FROM table1")) {
$query->execute();
$query->bind_result($compare_time);
$query->store_result();
$row_count = $query->num_rows;
if ($row_count > 0) {
   while ($query->fetch()) {
     if ($compare_time < $now) { // you reached the 1th of the next month time to update
         if ($query2 = $dbconnect->prepare("UPDATE table1 SET count_month=count_month +1, next_month=?")) {
         $query2->bind_param('i', $next_month);
         $query2->execute();
         $query2->close();
         }
     }
   }
}

$query->free_result();
$query->close();
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM