hashids类根据ID生成唯一字符串

问题描述:根据项目需求需要生成唯一字符串,考虑用处:生成客户邀请码,生成优惠券等

方法一:先给生成代码

   /**
    * 生成客户邀请码
    * @param  int      $user_id    唯一id
    * @return string   $code       邀请码
    */
    function createCode($user_id) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        $num = $user_id;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod].$code;
        }
        if(empty($code[3]))
            $code = str_pad($code,4,'0',STR_PAD_LEFT);
        return $code;
    }

       思路:先给出一个没有0的字符串,当做补位符号,比如小于四位的邀请码在高位补0,这样36个就变成了35个,然后把字符串顺序打乱,这样,在不知道$source_string的情况下,是没办法解出正确的唯一id的。

给出解码方法:

function decode($code) {
    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    if (strrpos($code, '0') !== false)
        $code = substr($code, strrpos($code, '0')+1);
    $len = strlen($code);
    $code = strrev($code);
    $num = 0;
    for ($i=0; $i < $len; $i++) {
        $num += strpos($source_string, $code[$i]) * pow(35, $i);
    }
    return $num;
}

该方法唯一不足在于有可能在知道$source_string字符串情况下反推出唯一的id

方法二:通过依赖安装hashids类(推荐)

由于项目是thinkphp5框架开发,通过composer安装了hashids类来生成

1、PHP环境邀请

php: ^5.6.4 || ^7.0

2、通过composer安装hashids类

composer require hashids/hashids

3、控制器代码

<?php
use Hashids\Hashids;
 
$id = 10;
$hashids = new Hashids('abc',4);
$code = $hashids->encode($id);

$id  = $hashids->decode($code);
var_dump($code,$id);
echo "<br>";

4、运行效果

string(4) "p1Ap" array(1) { [0]=> int(10) } 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值