PHP 短 ID 生成

    public static function generate(): 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;
    }
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 3

重复率有点高了,大概2%的重复率~

5天前 评论
王宣成 (楼主) 5天前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!