PHP 显示 01 而不是 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14645823/
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 07:40:53  来源:igfitidea点击:

PHP display 01 instead of 1

php

提问by Satch3000

Possible Duplicate:
Formatting a number with leading zeros in PHP

可能的重复:
在 PHP 中使用前导零格式化数字

I am populating a select box with php.

我正在用 php 填充一个选择框。

This is the code:

这是代码:

$select_month_control = '<select name="month" id="month">';
for($x = 1; $x <= 12; $x++) {
$select_month_control.= '<option value="'.$x.'"'.($x != $month ? '' : ' selected="selected"').'>'.date('F',mktime(0,0,0,$x,1,$year)).'</option>';
}
$select_month_control.= '</select>';

This is creating this:

这是创造这个:

<select id="month" name="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option selected="selected" value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>

The problem is that I need the 1, 2, 3 etc to be 01, 02, 03 etc... Like this:

问题是我需要 1、2、3 等为 01、02、03 等......像这样:

<option value="01">January</option>

instead of:

代替:

<option value="1">January</option>

How can I do this?

我怎样才能做到这一点?

回答by Masse

You can use sprintf("%02d", $number)to format strings.

您可以使用sprintf("%02d", $number)格式化字符串。

Edit: See http://www.php.net/manual/en/function.sprintf.phpfor more information about format strings

编辑:有关格式字符串的更多信息,请参见http://www.php.net/manual/en/function.sprintf.php

回答by Prasanth Bendra

user str_padref : http://php.net/manual/en/function.str-pad.php

用户str_pad参考:http: //php.net/manual/en/function.str-pad.php

$select_month_control = '<select name="month" id="month">';
for($x = 1; $x <= 12; $x++) {
$select_month_control.= '<option value="'.str_pad($x, 2, "0", STR_PAD_LEFT).'"'.($x != $month ? '' : ' selected="selected"').'>'.date('F',mktime(0,0,0,$x,1,$year)).'</option>';
}
$select_month_control.= '</select>';

回答by Lix

You might want to try using the str_pad()function within your loop :

您可能想尝试str_pad()在循环中使用该函数:

str_pad— Pad a string to a certain length with another string

str_pad— 用另一个字符串将一个字符串填充到一定长度

for($x = 1; $x <= 12; $x++) {
  $value = str_pad($x,2,"0",STR_PAD_LEFT);
  $select_month_control.= '<option value="'.$value.'">'.$value.'</option>';
}