(业务)自动生成邀请码

这里写自定义目录标题

背景

产品希望用户在注册的时候自动生成一个 【AB12】形式的邀请码。

思路

1.邀请码是字母加数字组合形式,并且可以看出以自增的方式创建。
2.采用ASCII码的形式处理字母部分('A-Z’的ASCII码为65-90)。
3.采用自左到右自增的方式完成。

简陋的代码

/**
     * 2022-06-16 获取一个新的邀请码
     * 唯一,且4位,[XX22]形式,可支持6w+账号,溢出为NULL
     * @return string|null
     */
    public function getNewInvitationCode(): string|null
    {
        # default
        $arr = [
            '65',# ASCII 065-090
            '65',
            '00'# int max 99
        ];

        $release_invitation_code = User::query()->withoutGlobalScope('activeUser')->orderByDesc('invitation_code')->value('invitation_code');
        if (!empty($release_invitation_code)) {
            preg_match_all('/\w/',$release_invitation_code,$tmp);
            $tmp = $tmp[0];
            $arr = [
                ord($tmp[0]),
                ord($tmp[1]),
                ($tmp[2].$tmp[3])
            ];
        }
        $arr_rev = array_reverse($arr);
        $next_location_increase = false;

        $num = str_pad($arr_rev[0] + 1, 2, 0, STR_PAD_LEFT);
        if ($num > 99) {
            $num = '00';
            $next_location_increase = true;
        }else {
            $num = str_pad($num,2,0, STR_PAD_LEFT);
        }
        if ($next_location_increase) {
            $c1 = $arr_rev[1] + 1;
            $next_location_increase = false;
            if ($c1 > 90) {
                $next_location_increase = true;
                $c1 = 65;
            }
        } else {
            $c1 = $arr_rev[1];
        }
        if ($next_location_increase) {
            $c2 = $arr_rev[2] + 1;
            $next_location_increase = false;
            if ($c2 > 90) {
                goto SET_NULL;
            }
        } else {
            $c2 = $arr_rev[2];
        }
        $arr = [$c2, $c1, $num];
        $invitation_code_rev = [
            $num,
            chr($c1),
            chr($c2),
        ];
        $invitation_code = implode('', array_reverse($invitation_code_rev));

        goto SET_CODE;
        SET_NULL:
        return null;
        SET_CODE:
        return $invitation_code;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值