PHP method of generating order number

The first way to generate unique order number in PHP

PHP code

$str = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
/**Bird and fish blog */
echo $str;

 

 

Note: this method is generated by using the current time plus random machine completion. Of course, we can make the time accurate to the second level

The second way to generate unique order number in PHP

Code

$str = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
 /**Bird and fish blog */
 echo $str;

 

Explanation: this method is similar to the first one, but it is more complicated than the first one

The third way to generate order number in PHP

 Code
//Generate 24 digit unique order number, format: YYYY-MMDD-HHII-SS-NNNN,NNNN-CC,
 //Where: YYYY = year, MM = month, DD = date, HH=24 format hour, II = minute, SS = second, nnnnnn = random number, CC = check code 
//Bird and fish blog
@date_default_timezone_set("PRC"); 
while(true){ 
//subscription date
$order_date = date('Y-m-d'); 
//Order number subject (YYYYMMDDHHIISSNNNNNNNN)
$order_id_main = date('YmdHis') . rand(10000000,99999999); 
//Order number body length
$order_id_len = strlen($order_id_main);
$order_id_sum = 0; 
for($i=0; $i<$order_id_len; $i++){    
    $order_id_sum += (int)(substr($order_id_main,$i,1));
}
//Unique order number (YYYYMMDDHHIISSNNNNNNNNCC)
$order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);

 

 

Note: does this code look very complicated? However, the code of this scheme is suitable for use on some large e-commerce websites. It can handle the subtle order number without repetition.

The fourth method

This fourth method is very interesting. When I saw this code, I was surprised by the person who wrote it.

Code

$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

 

Note: this method uses English letters, date, Unix time stamp, microseconds and random numbers. The possibility of repetition is greatly reduced, which is very good. The use of letters is very representative. A letter corresponds to a year, with a total of 16 digits, not many, not many.

Above there is a way to generate a unique order number using PHP. If it is not a very large e-commerce website, I recommend the second method, which is fast and efficient.

Tags: Programming PHP Unix

Posted on Tue, 05 Nov 2019 13:35:02 -0500 by maneetpuri