Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

php-IdCode

php 根据自增id创建唯一编号类

介绍

在开发过程中,我们数据表一般都使用 自增数字 作为 id主键,而 id 是数字型,不容易理解。

我们把 id 按一定格式转为编号后,很容易根据编号知道代表的是什么内容。


编号创建的规则

  • 唯一

    使用自增id生成,保证唯一性

  • 尽可能短

    可使用数字求余对应字母的方式处理,创建较短的编号


算法原理

  • 加自定义前缀,用于标识

  • 格式使用 前缀字母数字 组成,数字只保留N位,超过的使用数字求余的方式使用字母对应

  • 例如:

    id=1

    前缀=F

    数字保留3位

    则创建的编号为:F-A-001


演示

require 'IdCode.php';

$test_ids = array(1, 9, 10, 99, 100, 999, 1000, 1009, 2099, 3999, 9999, 14999, 25999, 26000, 99999);

foreach($test_ids as $test_id)
{
    echo $test_id.' = '. IdCode::create($test_id, 3, 'F').PHP_EOL;
}

输出:

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
25999 = F-Z-999
26000 = F-AB-000
99999 = F-VD-999