问题描述:根据项目需求需要生成唯一字符串,考虑用处:生成客户邀请码,生成优惠券等
方法一:先给生成代码
/**
* 生成客户邀请码
* @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) }