Table of Contents
回复内容:
Home Backend Development PHP Tutorial php订单号方案,重复的可能性要很低很低很低,大家说说自己的方案。

php订单号方案,重复的可能性要很低很低很低,大家说说自己的方案。

Jun 06, 2016 pm 08:41 PM
php

php订单号方案,重复的可能性要很低很低很低,大家说说自己的方案。

回复内容:

php订单号方案,重复的可能性要很低很低很低,大家说说自己的方案。

我的算法是:

买家UID+商家UID+年月日+三位随机数

大家觉得怎么样?

我来说下对京东ID编号的看法,两年前京东订单就突破2亿,现在应该超过四个亿了,十位订单最长才99亿,从这个占比来说,京东的订单号应该不是简单某种随机算法做出来的,如果是随机算法做出来的,肯定要做二次检验,ID是否已存在,如果存在就再生成新的。根据我分析自己在京东购买东西实际编号,丫就是按从小到大生成的
我估计有个外置ID生成服务器,要不然肯定抗不住双11这种,比如可以有一台专门服务器分多个进程,每个进程负责10万个编号分配,没有了就再申请,进程间的编号独立,或者简单点每台应用服务器就有个专属ID区域。

我们这的方式就是:
时间戳 + 机器编号 + 0-1000循环编号

首先时间戳是不会重复的,好像这样就保证了不重复吧。

我看了下淘宝的订单和账户有关。 同一个账户对同一个商家的订单号尾数好像。。是一样的

有反馈下面代码,不靠谱,冲撞率极高,这里就仅做学习,不推荐正式环境使用了

<code>    /**
     *
     * uniqid - 官方是这样说的:
     * Gets a prefixed unique identifier based on the current time in microseconds.
     */
    function build_order_no()
    {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }</code>
Copy after login

补充:来自ECSHOP订单号生成函数:/includes/lib_order.php文件中的get_order_sn()

<code>/**
 * 得到新订单号
 * @return  string
 */
function build_order_no()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
 
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}</code>
Copy after login

from :http://levi.cg.am/archives/3373

有一个东西叫 UKG 专门来干这个事情的。可以了解下:https://github.com/liexusong/ukg

我觉得uniqid就行
http://php.net/manual/zh/function.uniqid.php

可以 参考一下 ecshop 的订单生成机制

<code>return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); 
</code>
Copy after login

$str = date('ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
或者
$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn = $yCode[intval(date('Y')) - 1970] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%04d%02d', rand(1000, 9999), rand(0, 99));

上面的方案生成的订单号比较长,京东的十位订单号是怎么生成和保证不重复的呢?

订单编号在什么时候生成?怎样避免生成重复的?事务安全?存储过程?

sys_guid

为什么我想用hash做订单号……

<code>/*
 * 得到唯一的订单编号
 * @params null
 * @return string 订单编号
 */
/** preterchan **/
public function gen_id($n=0, $data_format='ymdHi')
{
    $i = rand(0,99999);
    do{
        if(99999==$i){
            $i=0;
        }
        $i++;
        $order_id = date($data_format).str_pad($i,5,'0',STR_PAD_LEFT);
        if ($n) $order_id .= $n;
        $row = $this->db->selectrow('SELECT order_id from orders where order_id ='.$order_id);
    }while($row);
    return $order_id;
} 
</code>
Copy after login

生成出的数字转换成36进制(数字+26个字母),可以缩短长度
比如 :

<code> //会员号 + 秒 + 微秒 + 随机
$mid=118914;
list($usec, $sec) = explode(" ", microtime());
$rand=rand(1000,9999);
echo strtoupper(base_convert($mid,10,36).base_convert($sec,10,36).base_convert($usec*10000000,10,36).base_convert($rand,10,36));
//2JR6NE7JXQ5SPY85BY
</code>
Copy after login

如果没有别的前提要求,自增长就足够了...
我之前一个项目的要求是不能让用户看出是怎么生成的,表面上看起来要完全随机
那么加时间戳也会被看出来,使用用户uid也会被看出来,随机生成又有可能出现重复
最后是这样做的

<code>        $time_order=time();
        list($usec, $sec)=explode(" ", microtime());
        $orderid=substr($uid*rand(11,55),0,5);
        $orderid.=date('ymdHis',$sec).ceil($usec*10);
        $orderid=substr($orderid,0,18);
</code>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles