【问题标题】:Can I use an if statement with multiple conditions? PHP我可以使用带有多个条件的 if 语句吗? PHP
【发布时间】:2017-03-29 07:15:45
【问题描述】:

我打赌我可以,但它会这样工作吗?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

因此,如果 $month 是 01,则 $dutchmonth 应该是 Januari。如果 $month 是 02,则 $dutchmonth 应该是 Februari,以此类推。 我觉得我做的不对?

【问题讨论】:

标签: php if-statement multiple-conditions


【解决方案1】:

就像你不会返回任何月份,因为你连接(0102 山不存在)。

如果我正确理解你的问题,我认为数组会更好:

$month = explode('-', $date)[1]; //Ok you use this data like an index

$letterMonth = ['01' => 'Januari', '02' => 'Februari', ....]; // Create an array with correspondance number -> letter month

$dutchmonth = $letterMonth[$month]; Get the good month using your index

【讨论】:

  • 谢谢,这看起来可以按我想要的方式工作。
【解决方案2】:

试试这个:

使用elseif 条件

if ($month == '01') {
    $dutchmonth = 'Januari';
} elseif ($month == '02') {
    $dutchmonth = 'Februari';
} elseif ($month == '03') {
   $dutchmonth = '...'; 
} 

【讨论】:

  • 这看起来效率很低:) 但是感谢您的帮助!
【解决方案3】:

创建查找数组并按键获取值:

$month = '02';
$months = [
    '01' => 'Januari'
    '02' => 'Februari'
    // more months here
];
$dutchmonth = isset($months[$month])? $months[$month] : '';
echo $dutchmonth;

【讨论】:

    【解决方案4】:

    我认为正确的方法是将地图保存为数组。 Demo

    <?php
    $array['01'] = 'Januari';
    $array['02'] = 'Februari';
    print_r($array);
    
    echo $array[$month];
    

    【讨论】:

      【解决方案5】:

      您可以执行以下任何操作:

      1. 否则

        if ($month == "01") {
            $dutchmonth = "Januari";
        } else if($month == "02"){
            $dutchmonth = "Februari";
        }
        
      2. 切换

        switch($month) {
            case "01":
                $dutchmonth = "Januari";
                break;
            case "02":
                $dutchmonth = "Februari";
                break;
        }
        
      3. 使用数组

        $month_arr = array('01' => "Januari", '02' => "Februari");
        $dutchmonth = $month_arr[$month];
        

      注意:要使用多个if 条件,请使用逻辑运算符 &&||

      【讨论】:

        猜你喜欢
        • 2013-05-13
        • 2017-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多