开发者

PHP: for loop and birthday date

开发者 https://www.devze.com 2023-01-14 16:51 出处:网络
I have a little problem birthday´s get stored as DATE in the MySQL database. DATE is 00-00-00 and now when i make the select options, i did it with a for loop:

I have a little problem

birthday´s get stored as DATE in the MySQL database.

DATE is 00-00-00

and now when i make the select options, i did it with a for loop:

<?php
$month_names = array("januar", "februar", "marts", "april", "maj", "juni", "juli", "august", "september", "oktober", "november", "december");
for ($i=1; $i<=12; $i++) {
    echo "<option ";
    if ($i == $month) {
        echo "selected=\"selected\" ";
    }
    echo "value=\"$i\">", $month_names[$i-1], 开发者_如何学运维"</option>\n";
}
?> 

This works, but gives me 1,2,3,4,5,6,7,8,9,10,11,12 as values.

I need to have it like this 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12.

How can i do this?


Replace the 7th line with the following:

printf("value=\"%02d\">%s</option>\n", $i, $month_names[$i-1]);


You need to put a condition like this:

for ($i=1; $i<=12; $i++) {
    echo "<option ";
    if ($i == $month) {
        echo "selected=\"selected\" ";
    }

    if ($i < 10) {
      echo "value=\"0$i\">", $month_names[$i-1], "</option>\n";
    }
    else{
      echo "value=\"$i\">", $month_names[$i-1], "</option>\n";
    }
}


str_pad() is what you're after.

http://www.php.net/str_pad

Instead of printing $i, you need to use

echo str_pad($i, 2, "0", STR_PAD_LEFT);

which will pad the string with zeros on the left-hand size until it is two characters long.


No need to use string formatting functions:

Change

echo "value=\"$i\">", $month_names[$i-1], "</option>\n";

to

echo "value=\"$i\">", ($month_names[$i-1] < 10 ? $month_names[$i-1] : "0" . $month_names[$i-1]), "</option>\n";


A simple approach would be to prepend the value string with a '0' if it's less than 10.

0

精彩评论

暂无评论...
验证码 换一张
取 消