用 PHP 中的一位、两位或三位整数生成 4 位整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11932058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:28:52  来源:igfitidea点击:

Make 4 digit integer from one, two, or three digits integer in PHP

phpinteger

提问by aspirinemaga

I'am doing a call to a database to retrieve an ID of a specific item. Usually there are the ids like: 1, 2, 14, 23, .... I need to get the ID from a DB and output it 4 digit number.

我正在调用数据库以检索特定项目的 ID。通常有像这样的ID:1, 2, 14, 23, .... 我需要从数据库中获取 ID 并输出 4 位数字。

For exemple: My result ID is: 1. Now i when i have this value, i want it to become 0001. Or if my result id is 13, it should became 0013, etc.

例如:我的结果 ID 是:1。现在,当我拥有此值时,我希望它成为0001. 或者如果我的结果 id 是13,它应该变成0013,等等。

How can i achieve that with php without changing the real ID in database?

如何在不更改数据库中的真实 ID 的情况下使用 php 实现这一点?

回答by Alix Axel

You want to zerofillan integer.

你想用零填充一个整数。

You could either do sprintf('%04u', $n)or str_pad($n, 4, '0', STR_PAD_LEFT).

你可以做sprintf('%04u', $n)str_pad($n, 4, '0', STR_PAD_LEFT)

回答by Ignacio Vazquez-Abrams

Same as always.

一如往常。

sprintf("%04d", $num)

回答by Fluffeh

You want the PHP strpadfunction:

你想要PHP strpad函数:

<?php
$input = 1;
echo str_pad($input, 4, "0", STR_PAD_LEFT);  // produces "0001"
?>

回答by Tim

If you want to do it inside of MySQL query, here it is

如果你想在 MySQL 查询中进行,这里是

SELECT LPAD(id, 4, '0') as modified_id FROM table;