1. 程式人生 > >php 生成唯一隨機碼

php 生成唯一隨機碼

/**
 * 建立邀請碼
 * @param $length
 * @return array
 * @author Mr lj
 */
function createInvitationCode($num=1,$length=8)
{
    $sign = ['_','#','$','&','*','-'];
    $mixedArr = array_merge(range('a','z'),range('A','Z'),range(0,9),$sign);
    $data = [];
    $i = 0;
    $str = '';

    for($a=0;$a<$num
;$a++) { while($i < $length) { $key = mt_rand(0,count($mixedArr)-1); $str .= $mixedArr[$key]; ++$i; } $res = M('SystemCode')->where(['code'=>$str])->find(); (($res == true) && --$a) || $data[] = $str;
$str = ''; $i = 0; } return $data; }