我在PHP中生成5位数序列号时遇到了问题。我想要的是,当用户调用PHP文件时,它将生成00001,然后下一次调用将生成00002,依此类推。然后在第二天,它将重新生成00001,00002,等等。例如:今天,我想生成从00001到99999的5位数序列,明天我想像昨天一样重新生成5位数序列。
发布于 2016-06-08 15:49:30
您需要使用sprintf来完成以下操作:
$num = 1;
echo sprintf("%'.05d\n", $num);但最终,这将是一个字符串。不是一个数字。使用上面的代码,会发生什么,当你发送号码时,说:
for ($num = 1; $num <= 50; $num++)
echo sprintf("%'.05d\n", $num);以上内容将为您提供:
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()这样的函数
function getSequence($num) {
return sprintf("%'.05d\n", $num);
}并对该数字调用函数:
$num = 756;
getSequence($num); // 00756输出
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希望我们编写代码。但现在它开始了。
要回答您的问题,您需要一个日期的服务器端计数器。比方说,今天的日期可以通过:
date("Ymd", strtotime("now")); // 20160608让我们这样做:
$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开始。
发布于 2016-06-08 15:56:10
明白了,你需要将值存储在数据库/文件中,并且在当天更改后,只需重置数据库/文件即可。
$i = readFromDBorFile();
$num = sprintf("%'.05d ", $i++);发布于 2016-06-08 16:08:17
您需要以某种方式保存计数器,以便下一次请求不会返回相同的数字。最简单的解决方案是将其保存到本地文件。
试试这个:
// 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);https://stackoverflow.com/questions/37696297
复制相似问题