如何让它为1-9渲染前导0?
<?php foreach (range(1, 12) as $month): ?>
<option value="<?=$month?>"><?=$month?></option>
<?php endforeach?>
答案 0 :(得分:7)
<?php foreach (range(1, 12) as $month): ?>
<option value="<?= sprintf("%02d", $month) ?>"><?= sprintf("%02d", $month) ?></option>
<?php endforeach?>
您可能希望将sprintf
的值保存到变量中,以避免多次调用它。
答案 1 :(得分:4)
答案 2 :(得分:2)
$month = 1;
echo sprintf("%02d", $month);
out: 01
使用sprintf
答案 3 :(得分:2)
array_map( function( $day ) {
return str_pad( $day, 2, '0', STR_PAD_LEFT );
}, range(1, 31) );
结果:
Array
(
[0] => 01
[1] => 02
[2] => 03
[3] => 04
[4] => 05
[5] => 06
[6] => 07
[7] => 08
[8] => 09
[9] => 10
[10] => 11
[11] => 12
[12] => 13
[13] => 14
[14] => 15
[15] => 16
[16] => 17
[17] => 18
[18] => 19
[19] => 20
[20] => 21
[21] => 22
[22] => 23
[23] => 24
[24] => 25
[25] => 26
[26] => 27
[27] => 28
[28] => 29
[29] => 30
[30] => 31
)
在PHP 5.3+中工作。自己尝试:https://3v4l.org/aE6HO
答案 4 :(得分:1)
if($month < 10) echo '0' . $month;
或
if($month < 10) $month = '0' . $month;