PHP 短 ID 生成

    public static function generateUniqueId(): string
    {
        $a = 53;      // 乘数,满足Hull - Dobell条件
        $c = 3;       // 加数,与模数互质
        $m = 26 ** 6; // 模数,26^6

        $microtime = microtime(true);
        $microtime = str_replace('.', '', $microtime);
        $randomNumber = random_int(100, 999);
        $seed = $microtime.$randomNumber; // 使用时间戳随机数作为种子
        $current = $seed % $m;

        $code = '';
        $num = $current;
        for ($j = 0; $j < 6; $j++) {
            $remainder = $num % 26;
            $code = chr(97 + $remainder).$code; // 转换为a - z
            $num = (int) ($num / 26);
        }
        // 计算下一个LCG值,为下一次调用做准备(如果需要)
        $current = ($a * $current + $c) % $m;

        return $code;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容