PHP生成唯一訂單號


function create_order_no() {
    $order_no = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);
    return $order_no;
}
function create_order_no() {
    $order_no = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).rand(1000,9999);
    return $order_no;
}

第三個基本不會重復,精確到毫秒,每毫秒還會隨機9999。經過這么處理,百分之99.99不會重復。

function create_order_no() {
    $order_no = date('Ymd').substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(1000, 9999));
    return $order_no;
}

測試

function create_order_no() {
    $order_no = date('Ymd').substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(1000, 9999));
    return $order_no;
}

$arr = [];
for ($i=0;$i<300000;$i++) {
    $arr[$i] = create_order_no();
}

print_r(array_unique($arr));

    [0]          =>  2018052442766315014567
    ...
    [299990] => 2018052442766316035660
    [299991] => 2018052442766316036736
    [299992] => 2018052442766316037720
    [299993] => 2018052442766316036546
    [299994] => 2018052442766316046898
    [299995] => 2018052442766316042222
    [299996] => 2018052442766316045190
    [299997] => 2018052442766316044156
    [299998] => 2018052442766316057563
    [299999] => 2018052442766316053670

經測試,一次生成30000個也沒有一個重復的。

再來一個簡單的,基本不會重復,需要關聯用戶id

function create_order_no($uid) {
    $order_no = date('Ym').$uid.substr(time(),3).rand(1000,9999); 
    return $order_no;
}

但這個會讓訂單長度不固定。
基本上第三個就夠用了。除非高並發,非常非常嚴重的時候,才會重復。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM