簡體   English   中英

如何使用PHP創建具有當前日期的10位隨機數

[英]How to create 10 digit random number with current date using PHP

我需要使用PHP創建具有當前日期的10位隨機數和一些輸入值。 我在下面解釋我的代碼。

$current_date=date('Y-m-d');//2018-04-30
$user_input=1;

以上數據是用戶輸入,我的預期輸出應在下面。

$output=1804300001

隨機數生成格式應類似於yymmdd4 digit number including user input 假設user_input = 1則應為0001user_input=12則應為0012如下所示。

像這樣

$date = new DateTime();
$input = 1;
$output = date_format($date,"ymd").sprintf('%04u', $input);
<?php

echo getToken(1);     #201804300001
echo getToken(9999);  #201804309999
echo getToken(12345); #201804301234


function getToken($input) {
    return date('Ymd').str_pad (substr($input, 0, 4) , 4, '0', STR_PAD_LEFT);
}

這里有一些適合您的代碼...有很多解決方案。

$user = 12;
$date = date("ymd", $time());
echo $datum .sprintf("%04u",$user);

最好的祝福

如果使用您的代碼( $current_date=date('Ym-d'); //2018-04-30 ):

$current_date = date('Y-m-d');
$user_input = 1;
$result = substr(str_replace('-', '', $current_date), 2); // Replace "-" with nothing plus remove first 2 digits
$result .= str_pad($user_input, 4, '0', STR_PAD_LEFT); // Fill in with "0" to the left

可能不是最漂亮的代碼,但效果很好。

暫無
暫無

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

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