我需要生成一组数字,包括当年,当月和以零开头的递增4位数字。有条件:
示例:
2020080023 -> last database record
2020080024 -> so this is will be the next record
示例:
2020080023 -> last database record on end of month
2020090001 -> so this is will be the next record
这是我到目前为止所拥有的:
$currentYear = date('Y');
$currentMonth = date('m');
$last4Digits = '0001';
$formatedNumber = $currentYear.$currentMonth.$last4Digits;
问题如何在最后一个记录的最后4位递增,以及如何在月初重置为0001?
答案 0 :(得分:0)
获取上一个记录的月份,并检查$ currentMonth和lastrecords月份是否相同(如果只是增加当前$ last4Digits,否则设置$ last4Digits ='0001'
$currentYear = date('Y');
$currentMonth = date('m');
// last record from db
$db_last4Digits = //data from db;
$db_last4Digits_month = substr($db_last4Digits, 4, 2);
$db_last4Digits_month = substr($db_last4Digits, 6);
if($db_last4Digits_month == $currentMonth){
$last4Digits = '0001'; // set to 0001 if current month is not equal to last month
}else{
$last4Digits = substr($db_last4Digits, -4, 4); //get last 4 numbers
$last4Digits += $last4Digits ;
}
$formatedNumber = $currentYear.$currentMonth.$last4Digits;
答案 1 :(得分:0)
该解决方案需要最后格式化的ID和一些逻辑。如果最后一个ID在当月,则只需将其增加1。如果不是,则新月从1开始。
function getId($lastId){
$curYm = (int)date('Ym');
$lastYm = (int)($lastId/10000);
if($lastYm == $curYm) return ++$lastId;
return $curYm * 10000 + 1;
}
示例:
$id = 2020080007;
$nextId = getId($id); //int(2020080008)
$id = 2020070127;
$nextId = getId($id); // int(2020080001)