【问题标题】:PHP month array original valuePHP月份数组原始值
【发布时间】:2020-08-22 15:44:53
【问题描述】:

我正在尝试通过表单提交一组日期。我已经弄清楚如何将数字范围显示为一个月,但是提交表单的格式错误。

工作:

$Startmonth=date('n');
$monthArray = range(1,12);
?>

<select class="bkwidgetdd" name="CIM" size="1">
    <!-- CIM = CheckInMonth -->
    <?php
    foreach ($monthArray as $month) {
        $selected = ($month == $Startmonth) ? 'selected' : '';
        echo '<option '.$selected.' value="'.$month.'">'.$month.'</option>';
    }
    ?>
</select>

不工作:

$Startmonth=date('n');
$monthArray = array(1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr', 5 => 'May', 6 => 'Jun', 7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Oct', 11 => 'Nov', 12 => 'Dec');
?>

<select class="bkwidgetdd" name="CIM" size="1">
    <!-- CIM = CheckInMonth -->
    <?php
    foreach ($monthArray as $month) {
        $selected = ($month == $Startmonth) ? 'selected' : '';
        echo '<option '.$selected.' value="'.$month.'">'.$month.'</option>';
    }
    ?>
</select>

我知道它会出错,因为它将月份作为字符串而不是数字值提交。如何让它显示为月份但提交为数字?

非常感谢。

【问题讨论】:

    标签: php arrays date


    【解决方案1】:

    你已经接近了,需要将数组的键用作值:

    foreach ($monthArray as $key => $month) {
        $selected = ($key == $Startmonth) ? 'selected' : '';
        echo '<option '.$selected.' value="'.$key.'">'.$month.'</option>';
    }
    

    【讨论】:

    • 需要用 key 检查 $key == $Startmonth ,
    【解决方案2】:

    请使用以下代码:

        $Startmonth=date('n');
        $monthArray = array(1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr', 5 => 'May', 6 => 'Jun', 7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Oct', 11 => 'Nov', 12 => 'Dec');
    ?>
    
    <select class="bkwidgetdd" name="CIM" size="1">
         <!-- CIM = CheckInMonth -->
         <?php
              foreach ($monthArray as $key => $month){
                  $selected = ($key == $Startmonth) ? 'selected' : '';
                  echo '<option '.$selected.' value="'.$key.'">'.$month.'</option>';
              }
         ?>
    </select>
    

    【讨论】:

    • 感谢 Suresh 的回复,标记了另一个,因为它首先出现。不过欣赏它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多