2017-03-29 69 views
-1

我敢打赌,我可以,但会这样工作吗?我可以使用多条件的if语句吗? PHP

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,依此类推。 我有这种感觉,我没有这样做的权利?

+0

使用'switch'而不是'if' http://php.net/manual/en/control-structures.switch.php – JapanGuy

+0

为什么不使用'switch' case? –

回答

0

试试这个:

使用elseif条件

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

这似乎非常低效:)但谢谢你的帮助! – user3625849

0

创建查找数组,通过键获取值:

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

我认为正确的方法是在地图保存一个阵列。原因您连接(芒斯0102不存在)Demo

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

echo $array[$month]; 
1

像thatyou不会返回任何一个月。

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

$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 
+0

谢谢,这看起来像是可以按我想要的方式工作的东西。 – user3625849

0

你可以做这些:

  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条件下使用逻辑运算符& &||

相关问题