【问题标题】:Handling month in switch case PHP在 switch case PHP 中处理月份
【发布时间】:2014-03-24 12:20:51
【问题描述】:

我想获取当前月份并添加接下来的三个月并将其显示在我的表格标题中。

我的代码是:

    $mon = (date('M')); 
    switch($mon) {
    case 'Mar' :  
    echo  '<th>Mar</th>';
    echo  '<th>Apr</th>';
    echo  '<th>May</th>';
    break;
    case 'Apr' :  
    echo  '<th>Apr</th>';
    echo  '<th>May</th>';
    echo  '<th>Jun</th>';
    break;
    }

    ............... and so on ..............

上述开关盒将在十二个月内完成其工作。 有没有办法在所有 12 个月内使用单个开关盒而不是 12 个开关盒动态地做到这一点? 我疯了吗?

谢谢, 金兹

【问题讨论】:

标签: php loops switch-statement


【解决方案1】:

您也可以自己计算接下来的几个月:

$now = time();
$currentMonth = date('n', $now);
$year = date('Y', $now);
$nextMonth = $currentMonth + 1;
$secondNextMonth = $currentMonth + 2;

echo  '<th>' . date('M', $now) . '</th>';
echo  '<th>' . date('M', mktime(0, 0, 0, $nextMonth, 1, $year)) . '</th>';
echo  '<th>' . date('M', mktime(0, 0, 0, $secondNextMonth, 1, $year)) . '</th>';

【讨论】:

  • mktime 实际上会自行回绕,您无需重新设置回1。实际上,您在该代码中有一个错误,并且将在 12 月获得两次 1 月。除此之外,很好的解决方案。
  • 我以为你在谈论日参数。我根据您的建议调整了代码。感谢您的提示。
【解决方案2】:

为什么不直接打印值?

<?php
echo '<th>'.date('M').'</th>';
echo '<th>'.date('M',strtotime("+1 months")).'</th>';
echo '<th>'.date('M',strtotime("+2 months")).'</th>';

【讨论】:

  • 这可能会在 1 月 31 日为您提供错误的结果。 “+1 个月”有点变化无常,因为“1 个月”是一个模糊的规范。
【解决方案3】:

您可以使用 strtotime 来获取接下来的几个月:

echo  '<th>' . date('M') . '</th>';
echo  '<th>' . date('M', strtotime('+1 months')) . '</th>';
echo  '<th>' . date('M', strtotime('+2 months')) . '</th>';

【讨论】:

  • 这可能会在 1 月 31 日为您提供错误的结果。 “+1 个月”有点变化无常,因为“1 个月”是一个模糊的规范。
【解决方案4】:

这是一个简单易懂的代码。试试看

$month = array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
for($i=0;$i<=11;$i++)
{
    if(date('M') == $month[$i])
    {
        $a = $i + 1;
        $b = $i + 2;
        if($a > 11)
        {
            $a = 0;
            $b = 1;
        }
        if($b > 11)
        {
            $b = 0;
        }
        echo  '<th>' . $month[$i] . '</th>';
        echo  '<th>' . $month[$a] . '</th>';
        echo  '<th>' . $month[$b] . '</th>';
    }
}

【讨论】:

  • 通俗易懂?也许。简单的?并不真地。 ;)
  • @deceze 这对每个人来说可能并不简单,但对你来说却很简单。我检查了你的 stackoverflow 个人资料 ;-) 对你来说应该是在公园里散步 :-D
  • 不是说我不懂,相反。我是说它过于复杂,而不是“简单”。 :) 对我来说,“简单”意味着“简洁,而不是冗长”。
  • @deceze 是的,我从 ';-)' 中得到了这个,不是真的。我只是在拉你的腿;-) :-)
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 2021-11-01
  • 1970-01-01
  • 2013-07-12
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多