生成订单编号


 

function get_order_sn( $type = 2,$prefix = null): string
{
    switch ($type) {
        case 1:
            $number = date('Ymd').substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

            break;

        case 2:
            // 雪花算法
            SnowFlake::machineId(env('server.machine_id',1));
            $number = SnowFlake::createOnlyId();

            break;

        default:
            $number = null;

            break;
    }

    return $prefix.$number;
}

 

雪花算法

class SnowFlake
{
    public const EPOCH = 1698136091489;    // 开始时间,固定一个小于当前时间的毫秒数
    public const max12bit = 4095;
    public const max41bit = 1099511627775;

    public static $machineId;      // 机器id

    public static function machineId($mId = 0)
    {
        self::$machineId = $mId;
    }

    public static function createOnlyId()
    {
        // 时间戳 42字节
        $time = floor(microtime(true) * 1000);
        // 当前时间 与 开始时间 差值
        $time -= self::EPOCH;
        // 二进制的 毫秒级时间戳
        $base = decbin(self::max41bit + $time);
        // 机器id  10 字节
        if (!self::$machineId) {
            $machineId = self::$machineId;
        } else {
            $machineId = str_pad(decbin(self::$machineId), 10, '0', STR_PAD_LEFT);
        }
        // 序列数 12字节
        $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, '0', STR_PAD_LEFT);
        // 拼接
        $base = $base.$machineId.$random;
        // 转化为 十进制 返回
        return bindec($base);
    }
}
发布时间 : 2023-02-28,阅读量:880 , 分类: PHP
本文链接:https://upwqy.com/details/18.html
微信JSAPI支付(一)准备工作 PHP 获取访问来源