我正在寻找一个使用字母和数字的解决方案,例如
故障代码:AF-5754
因为这些涉及到存储在数据库中的错误我需要它们是唯一的数据库中的id只是一个数字
有什么可行的方法呢
function randomstring($len)
{
$string = "";
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<$len;$i++)
$string.=substr($chars,rand(0,strlen($chars)),1);
return $string;
}
这将返回一个随机字符串,但通过电话读出它不是非常用户友好
答案 0 :(得分:1)
为什么不从sql id自动生成的唯一生成人类友好代码?
<?php
function getFrom($id) // Get a human-friendly code for unique id from database
{
$prefixes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Prefix posibilities
$primaryPrefx = "A"; // Another prefix to increase id limit
if($id > 259999)
{
$primaryPrefx = $prefixes[intval($id / 2600000)];
$id = $id % 2600000;
}
$prefix = ""; // Prefix to be used
$errorCode = ""; // The integer to be added after the prefix
$prefix = $prefixes[intval($id / 100000)]; // get the prefix based on $id ( < 10000 => A , 10000 => B, 20000 => C, 30000 => D etc...)
$id = $id % 100000; // now for the integer part (% returns remainder of division. This gets rid of > 9999 part)
if($id < 10000)
{
$errorCode .= "0"; // We need five digits after prefix
if($id < 1000)
{
$errorCode .= "0"; // We need five digits after prefix
if($id < 100)
{
$errorCode .= "0"; // We need five digits after prefix
if($id < 10)
{
$errorCode .= "0" . $id;
}
else
$errorCode .= $id;
}
else
$errorCode .= $id;
}
else
$errorCode .= $id;
}
else
$errorCode = $id;
return $primaryPrefx . "" . $prefix . "-" . $errorCode;
}
echo getFrom(1568110); // Gives AP-68110
?>
适用于ids&lt; 67599999
Code =&gt; id功能
function getIdFromCode($code)
{
$prefixes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$id = 0;
$id += strrpos($prefixes, $code[0]) * 260000; // first prefix
$id += strrpos($prefixes, $code[1]) * 100000; // second prefix
$id += intval(substr($code, 3)); // AA- is removed
return $id;
}
echo getIdFromCode("AP-68110"); // Gives 1568110