本文主要介绍了php根据自增id创建唯一编号类的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧
在开发过程中,我们数据表一般都使用自增数字作为id主键,而id是数字型,不容易理解。我们把id按一定格式转为编号后,很容易根据编号知道代表的是什么内容。
例如订单表id=20160111197681234,只看id我们并不知道这个id是订单表的id,而转为编号o-20160111197681234,则很容易看出是订单表的记录,然后可以根据id在订单表中搜寻。
编号创建的规则
1.唯一
使用自增id生成,保证唯一性
2.尽可能短
可使用数字求余对应字母的方式处理,创建较短的编号
算法原理
1.加自定义前缀,用于标识
2.格式使用前缀+字母+数字组成,数字只保留n位,超过的使用数字求余的方式使用字母对应
例如:
id=1
前缀=f
数字保留3位
则创建的编号为:f-a-001
代码如下:
idcode.class.php
<?php
/**
* php 根据自增id创建唯一编号类
* date: 2016-11-27
* author: fdipzone
* ver: 1.0
*
* func
* public create 创建编号
*/
class idcode{ // class start
/**
* 创建编号
* @param int $id 自增id
* @param int $num_length 数字最大位数
* @param string $prefix 前缀
* @return string
*/
public static function create($id, $num_length, $prefix){
// 基数
$base = pow(10, $num_length);
// 生成字母部分
$pision = (int)($id/$base);
$word = '';
while($pision){
$tmp = fmod($pision, 26); // 只使用26个大写字母
$tmp = chr($tmp + 65); // 转为字母
$word .= $tmp;
$pision = floor($pision/26);
}
if($word==''){
$word = chr(65);
}
// 生成数字部分
$mod = $id % $base;
$digital = str_pad($mod, $num_length, 0, str_pad_left);
$code = sprintf('%s-%s-%s', $prefix, $word, $digital);
return $code;
}
} // class end
?>
demo.php
<?php
require 'idcode.class.php';
$test_ids = array(1,9,10,99,100,999,1000,1009,2099,3999,9999,14999,99999);
foreach($test_ids as $test_id){
echo $test_id.' = '.idcode::create($test_id, 3, 'f').'<br>';
}
?>
输出:
1 = f-a-001
9 = f-a-009
10 = f-a-010
99 = f-a-099
100 = f-a-100
999 = f-a-999
1000 = f-b-000
1009 = f-b-009
2099 = f-c-099
3999 = f-d-999
9999 = f-j-999
14999 = f-o-999
99999 = f-vd-999
以上就是本文的全部内容,希望对大家的学习有所帮助。
相关推荐:
php实现通过strace定位故障原因的方法
php使用file_get_contents发送http请求功能简单
php+mysql高并发加锁事务处理问题解决方法
以上就是php 根据自增id创建唯一编号类的方法的详细内容。
