PHP根据id生成邀请码

xiaoxiao2021-02-28  24

方案一、id生成器本身就是一个不重复的数字,但长度过长还不美观,不符合邀请码的常用形式;

$code = "{$userId}{$currentTime}"

方案二、再有就是生成一个随机数,再从数据库里面查询看是否存在。缺点就是需要链接查询数据库,数据量大时耗时比较久;

while(true){    //获取一个随机字符串    $code = getRandString(8);    //判断该字符串是否存在    if( ! checkExists($code))        return $code;}

方案三、既然id是不会重复的数据,那么把id转换为36进制的字符串就好了。

function createCode($userId){    static $sourceString = [        0,1,2,3,4,5,6,7,8,9,10,        'a','b','c','d','e','f',        'g','h','i','j','k','l',        'm','n','o','p','q','r',        's','t','u','v','w','x',        'y','z'    ];    $num = $userId;    $code = '';    while($num)    {        $mod = $num % 36;        $num = (int)($num / 36);        $code = "{$sourceString[$mod]}{$code}";//邀请码拼接    }    //判断code的长度    if( empty($code[4]))        str_pad($code,5,'0',STR_PAD_LEFT);//长度不够拼接'0'    return $code;}

转载请注明原文地址: https://www.6miu.com/read-2596072.html

最新回复(0)