【码】生成唯一编码
in 代码片段 with 0 comment

【码】生成唯一编码

in 代码片段 with 0 comment

代码来源:自己整理编写
说明:由于游戏需要激活码,这样就迫使我去想办法生成一个全局绝对唯一的字符串,想来想去就成了下面这段代码,将字符串分为4段,前三段用数组排重,最后一段是随机的5个字符,然后用随机的组合形成想要的最终串。

public function createKeys(){
        $num = intval(I('post.num'));
        if( !$num ){
            $this->error("请输入条数!");
        }
        $packageId = I('post.packageId');
        $first  = array_keys($this->getKeyArr(1000));
        $second  = array_keys($this->getKeyArr(1000));
        $third  = array_keys($this->getKeyArr(1000));
        for( $i = 0; $i < $num; $i++ ){
            $key1 = mt_rand(0,999);
            usleep(10);
            $key2 = mt_rand(0,999);
            usleep(10);
            $key3 = mt_rand(0,999);
            usleep(10);
            $data = [];
            $data['key'] = "{$first[$key1]}-{$second[$key2]}-{$third[$key3]}-".StringOrg::randString(5);
            $data['key'] = strtoupper($data['key']);
            $data['packageId'] = $packageId;
            $data['addTime'] = NOW_TIME;
            GC('GiftNum')->add($data);
        }
        $this->success("操作成功!");
    }

    private function getKeyArr( $n, $result = [] ){
        for( $i=0; $i<$n; $i++ ){
            $resultKey = strtoupper(StringOrg::randString(5));
            $result[$resultKey] = $i;
        }
        $resultCount = count($result);
        if( $resultCount < $n ){
            usleep(50);
            $need = $n - $resultCount;
            return $this->getKeyArr( $need, $result );
        }else{
            return $result;
        }
    }
Comments are closed.