首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建5位序列号

如何创建5位序列号
EN

Stack Overflow用户
提问于 2016-06-08 15:45:36
回答 4查看 13.7K关注 0票数 1

我在PHP中生成5位数序列号时遇到了问题。我想要的是,当用户调用PHP文件时,它将生成00001,然后下一次调用将生成00002,依此类推。然后在第二天,它将重新生成00001,00002,等等。例如:今天,我想生成从00001到99999的5位数序列,明天我想像昨天一样重新生成5位数序列。

EN

回答 4

Stack Overflow用户

发布于 2016-06-08 15:49:30

您需要使用sprintf来完成以下操作:

代码语言:javascript
复制
$num = 1;
echo sprintf("%'.05d\n", $num);

但最终,这将是一个字符串。不是一个数字。使用上面的代码,会发生什么,当你发送号码时,说:

代码语言:javascript
复制
for ($num = 1; $num <= 50; $num++)
    echo sprintf("%'.05d\n", $num);

以上内容将为您提供:

代码语言:javascript
复制
00001  // type: String. Use intval() to get the integral value.
00002  // type: String. Use intval() to get the integral value.
00003  // type: String. Use intval() to get the integral value.

诸若此类。好的方面是,使用像getSequence()这样的函数

代码语言:javascript
复制
function getSequence($num) {
  return sprintf("%'.05d\n", $num);
}

并对该数字调用函数:

代码语言:javascript
复制
$num = 756;
getSequence($num); // 00756

输出

代码语言:javascript
复制
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050

小提琴:

更新: The OP希望我们编写代码。但现在它开始了。

要回答您的问题,您需要一个日期的服务器端计数器。比方说,今天的日期可以通过:

代码语言:javascript
复制
date("Ymd", strtotime("now")); // 20160608

让我们这样做:

代码语言:javascript
复制
$today = date("Ymd", strtotime("now"));
// Check if there's a file with the name exists:
if (file_exists($today)) {
  // Nothing to do. :)
} else {
  file_put_contents($today, 0);
}
$count = file_get_contents($today);
$count++;
echo sprintf("%'.05d\n", $count);

这将获得当天的计数,每天,第二天,它从1开始。

票数 4
EN

Stack Overflow用户

发布于 2016-06-08 15:56:10

明白了,你需要将值存储在数据库/文件中,并且在当天更改后,只需重置数据库/文件即可。

代码语言:javascript
复制
$i = readFromDBorFile();
$num = sprintf("%'.05d&nbsp;", $i++);
票数 0
EN

Stack Overflow用户

发布于 2016-06-08 16:08:17

您需要以某种方式保存计数器,以便下一次请求不会返回相同的数字。最简单的解决方案是将其保存到本地文件。

试试这个:

代码语言:javascript
复制
// let's store the file name
$filename = 'counter.txt';

// create the file if it doesn't exist
if (!file_exists($filename)) {
    $counter_file = fopen($filename, "w");
    fwrite($counter_file, "0");
    $counter = 0
} else {
    $counter_file = fopen($filename, "r");

    // will read the first line
    $counter = fgets($counter_file)
}

// increase $counter
$counter++;

// echo counter
echo $counter

// save the increased counter
fwrite($counter_file, "0");

// close the file
fclose($counter_file);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37696297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档