Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
月格式php_Php - Fatal编程技术网

月格式php

月格式php,php,Php,我只是php的初学者。我正在尝试使用以下代码打印月份数组 <?php $totalmonth=12; for($startmonth=01; $startmonth<=$totalmonth; $startmonth++) { $montharr[]=$startmonth; } print_r($montharr); ?> 我该怎么做呢?PHP有许多日期函数,这些函数可能会为您试图实现的目标提供更好的解决方案,但一种非常快速而肮脏的方法是检查数字是否低于10,然后在

我只是php的初学者。我正在尝试使用以下代码打印月份数组

<?php
$totalmonth=12;
for($startmonth=01; $startmonth<=$totalmonth; $startmonth++)
{
    $montharr[]=$startmonth;
}
print_r($montharr);
?>

我该怎么做呢?

PHP有许多日期函数,这些函数可能会为您试图实现的目标提供更好的解决方案,但一种非常快速而肮脏的方法是检查数字是否低于10,然后在前面加上一个零:

<?php
$totalmonth=12;
for($startmonth=1; $startmonth<=$totalmonth; $startmonth++)
{
    // Check amount
    if($startmonth < 10) {
        $montharr[]='0'.$startmonth;
    } else {
        $montharr[]=$startmonth;
    }
}
print_r($montharr);
?>

PHP有许多日期函数,这些函数可能会为您试图实现的目标提供更好的解决方案,但一种非常快速且肮脏的方法是检查数字是否低于10,然后在前面加上一个零:

<?php
$totalmonth=12;
for($startmonth=1; $startmonth<=$totalmonth; $startmonth++)
{
    // Check amount
    if($startmonth < 10) {
        $montharr[]='0'.$startmonth;
    } else {
        $montharr[]=$startmonth;
    }
}
print_r($montharr);
?>

使用str\u pad

<?php
$totalmonth=12;
for($startmonth=1; $startmonth<=$totalmonth; $startmonth++)
{
    $montharr[]=str_pad($startmonth, 2, "0", STR_PAD_LEFT);
}
print_r($montharr);
?>

使用str\u pad

<?php
$totalmonth=12;
for($startmonth=1; $startmonth<=$totalmonth; $startmonth++)
{
    $montharr[]=str_pad($startmonth, 2, "0", STR_PAD_LEFT);
}
print_r($montharr);
?>

例如
sprintf

例如
sprintf

您可以将其打印为字符串

例如:

<?php
  $month = sprintf("%02d", $month);
您可以使用将其打印为字符串

例如:

<?php
  $month = sprintf("%02d", $month);

使用PHP内置的str_pad:

<?php
$totalmonth=12;
for($startmonth=01; $startmonth<=$totalmonth; $startmonth++)
{
    $montharr[] = str_pad($startmonth, 2, '0', STR_PAD_LEFT);
}
print_r($montharr);
?>

使用PHP内置的stru\u pad:

<?php
$totalmonth=12;
for($startmonth=01; $startmonth<=$totalmonth; $startmonth++)
{
    $montharr[] = str_pad($startmonth, 2, '0', STR_PAD_LEFT);
}
print_r($montharr);
?>

通过将字符串隐式转换为字符串,强制插入字符串:

 $montharr[]= "" + $startmonth;

通过将字符串隐式转换为字符串,强制插入字符串:

 $montharr[]= "" + $startmonth;