提问人:codingDummy 提问时间:8/10/2023 最后编辑:codingDummy 更新时间:8/10/2023 访问量:49
将基于传入值的数字转换为至少 6 位和最多 8 位
turn a number based on passed in value to at least 6 digit and max 8 digit
问:
public static function generateReceiptNumber(int $id)
{
$receipt_number = sprintf('%06d', $id % 100000000);
return $receipt_number;
}
我有上面的代码来帮助我将传入的$id转换为最小 6 位和最多 8 位数字。例如:000001 - 99999999
但是这个代码有一个缺陷,当$id等于 100000000 时,它会返回我 000000, 我怎样才能增强上面的代码,让我000001?
依此类推,$id是数据库增量 ID。
想要实现这一点的目的是因为,我有一个显示文本框,其文本限制只有 8 位,我只能将数字重新启动回000001并继续计数重复。
答:
0赞
Ravi Rathore
8/10/2023
#1
public static function generateReceiptNumber(int $id)
{
// Handle the special case when $id is 100000000
if ($id === 100000000) {
return '000001';
}
// Use modulo to limit the ID to the range 0 to 99,999,999
$limited_id = $id % 100000000;
// Format the limited ID with leading zeros to ensure at least 6 digits
$receipt_number = sprintf('%06d', $limited_id);
return $receipt_number;
}
如果对您有所帮助,请查看此答案。
评论
1赞
codingDummy
8/10/2023
感谢您的解决方案。但是,当$id等于 1000000000 时,它将返回 000000 而不是 000001
3赞
Olivier
8/10/2023
#2
这个怎么样:
function generateReceiptNumber(int $id)
{
while($id>=100000000)
$id -= 100000000 - 1;
return sprintf('%06d', $id);
}
评论
0赞
codingDummy
8/10/2023
这个解决方案太棒了,谢谢。但是,当 $id 等于 999999999 时,它将返回 100000000 而不是 000001
0赞
Olivier
8/10/2023
@codingDummy我更新了代码。
0赞
codingDummy
8/10/2023
出色的解决方案,谢谢巴德。欣赏
0赞
Eng Cy
8/10/2023
绝妙的解决方案,我刚才很努力,但没能成功,我现在学到了一些东西
评论
$id
作为数据库增量 ID,不需要您执行这些操作。