# 生成一个可逆的短编码

```/**
* 生成一个短的编号
* @param \$input
* @param int \$neededLength
* @param string \$alphabet
* @return string
*/
public function gen_short_id(\$input, \$neededLength = 8, \$alphabet = '0123456789') {
\$output = '';
\$base = strlen(\$alphabet);
if (is_numeric(\$neededLength)) {
\$neededLength--;
if (\$neededLength > 0) {
\$input += pow(\$base, \$neededLength);
}
}
for (\$current = (\$input != 0 ? floor(log(\$input, \$base)) : 0); \$current >= 0; \$current--) {
\$powed = pow(\$base, \$current);
\$floored = floor(\$input / \$powed) % \$base;
\$output = \$output . substr(\$alphabet, \$floored, 1);
\$input = \$input - (\$floored * \$powed);
}
return \$output;
}

/**
* 解析一个短的编号
* @param \$input
* @param int \$neededLength
* @param string \$alphabet
* @return float|int
*/
public function decode_short_id(\$input, \$neededLength = 8, \$alphabet = '0123456789') {
\$output = 0;
\$base = strlen(\$alphabet);
\$length = strlen(\$input) - 1;
for (\$current = \$length; \$current >= 0; \$current--) {
\$powed = pow(\$base, \$length - \$current);
\$output = (\$output + strpos(\$alphabet, substr(\$input, \$current, 1)) * \$powed);
}
if (is_numeric(\$neededLength)) {
\$neededLength--;
if (\$neededLength > 0) {
\$output -= pow(\$base, \$neededLength);
}
}
return \$output;
}
```