Skip to content

Instantly share code, notes, and snippets.

@wolf432
Created September 28, 2016 07:57
Show Gist options
  • Save wolf432/9d8c7079fa9442e2139ff2ab11a4804b to your computer and use it in GitHub Desktop.
Save wolf432/9d8c7079fa9442e2139ff2ab11a4804b to your computer and use it in GitHub Desktop.
根据一个批次id获取一批优惠券。根据优惠券获取批次id
<?php
$code = createCode(1,6);
echo code2Id($code[0]);
/**
* 根据id获取一组随机字符串
*
* @param mixed $batch_id
* @param mixed $num
* @access public
* @return void
*/
function createCode($batch_id, $num)
{/*{{{*/
$length = 12;
$index = 0;
$minlen = 5; //最短随机码长度 每个学习码最低有5个是随机码
$joinStr = 'X'; //学习码连接符
$codes = 'ABCDEFGHJKMNPQRSTUVWY123456789'; //学习码包含的字符串
$codeArr = array();
for($i=0;$i<$num;$i++){
$code = LTS($batch_id) . $joinStr;
$code .= LTS($index) . $joinStr;
$tmplen = $length - strlen($code);
$code .= randCode($tmplen,$codes);
//使用- 分隔
$tmpcode = '';
for($j=0;$j<$length;$j++){
if($j > 0 && $j%4 == 0) $tmpcode .= '-';
$tmpcode .= $code[$j];
}
$code = $tmpcode;
$codeArr[] = $code;
$index++;
}
return $codeArr;
}/*}}}*/
/**
* 根据加密串来获取生成的批次id
*
* @param mixed $code
* @access public
* @return void
*/
function code2Id($code)
{/*{{{*/
list($id) = explode("X",$code[0]);
return STL($id);
}/*}}}*/
/**
* 将数字转换为字符串 -- 和函数 STL 配合使用 还原数字 例如: STL(LTS(125689))=125689
*
* @author chendong 2014-04-10
* @param int $long 要转换的数字
* @param str $codes 依据该字符码转换数字
* @return str $code
* */
function LTS($long,$codes='YM6BU9RTN8WSV5HD32GJC4Q1K7EFAP')
{/*{{{*/
$len = strlen($codes);
$long = intval($long);
$short = '';
do {
$short = $codes[$long % $len] . $short;
$long = intval($long / $len);
} while ($long != 0);
return $short;
}/*}}}*/
/**
* 将函数LTS加密过的数字字符码还原为数字
*
* @author chendong 2014-04-10
* @param str $short
* @param str $codes 依据该字符码还原数字,需和函数LTS的字符码一样
* @return int $long
**/
function STL($short,$codes='YM6BU9RTN8WSV5HD32GJC4Q1K7EFAP')
{/*{{{*/
$len = strlen($codes);
$codeArr= array();
for($i=0 ; $i < $len; $i++){
$codeArr[$codes[$i]] = $i;
}
$long = 0;
$short = strtoupper(strval($short));
$num = strlen($short);
for ($n = 0; $n < $num; $n++) {
if($codeArr[$short[$n]] !== 0 && empty($codeArr[$short[$n]])) return false;
$long *= $len;
$long += $codeArr[$short[$n]];
}
return $long;
}/*}}}*/
/**
* 获取一个指定长度的随机码
*
* @author chendong 2014-04-10
* @param int $num
* @param str $codes 随机码包含的字符串
* @return str $code
**/
function randCode($num,$codes='ABCDEFGHJKMNPQRSTUVWY123456789')
{/*{{{*/
$len = strlen($codes) - 1;
$code = '';
for($i=0;$i<$num;$i++){
$nums = rand(0,$len);
$code .= $codes[$nums];
}
return $code;
}/*}}}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment