我想介绍使用 MySQL 表字段 (question_id) 中带有自动增量的整数的短 uniq 字符串 ID。
示例 当用户指向 www.something.com/SjBWY -> php 将获取 id=23511 的记录;
我想隐藏有关问题数量的信息并引入 question_code,它将使用某种翻译算法 1 对 1 映射到 question_id。 我不想将 question_code 存储在数据库中,我相信 MySQL 开发人员比我更聪明,并且已经创建了可靠的机制来生成 uniq 数字。
朴素的方法:(http://ideone.com/rK4hzx)
$num = 11231;
while($num > 0) {
$v = ord( $num % 10);
$v += 25;
echo chr($v);
$num = round($num / 10);
}
// JLKJJ
$result = array_reverse(str_split('JLKJJ'));
foreach ($result as $single) {
echo chr(ord( $single)-25);
}
// 11231
问题:您能提出更好的解决方案吗?
朴素的弱点:
- 我希望能够使用大小写字母
- 我希望能够尽可能将字符串长度限制为 5。
- 在生成的字符串中不应该是明显的序列。 11 的值应尽可能远离 12。
编辑 算法应该是对称的,这意味着我可以翻译 Int->String 和 String->Int。 MD5 和其他哈希算法只是一种方式,我无法从 String->Int 翻译
最佳答案
终于找到我要找的东西了。它被称为: http://www.hashids.org/它有 php、java、nodejs、ruby、.net 等版本。
Hashids was designed for use in URL shortening, tracking stuff, validating accounts or making pages private (through abstraction). Instead of showing items as 1, 2, or 3, you could show them as b9iLXiAa, EATedTBy, and Aaco9cy5. Hashes depend on your salt value.
关于php - 将整数 ID 转换为字符串的对称算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16883411/