【问题标题】:Switch case with case 2 equal to case 1 plus case 0用 case 2 切换 case 等于 case 1 加上 case 0
【发布时间】:2013-08-14 15:34:26
【问题描述】:

我有一个switch statement,当$value == 2 开关应该发布与case 0case 1 相同的内容时。

switch($value){
    case 0:
        print '<tr>';
        print '<td align="right">';
        print "Sup:";
        print '</td>';
        print '<td>';
        print $sup;
        print '</td>';
        print '</tr>';
    break;  

    case 1:
        print '<tr>';
        print '<td align="right">';
        print "Inf:";
        print '</td>';
        print '<td>';
        print $inf;
        print '</td>';
        print '</tr>';
    break;

    case 2:
      //this case should post case 0 and case 1 together
    break;
}

【问题讨论】:

  • 然后将您的打印语句放入函数中并使用您的案例调用这些函数可能会更容易
  • $value == 2 应该同时做case 1和case 0?

标签: php switch-statement case


【解决方案1】:

为什么不这样:

function case0() {
   print '<tr>';
   print '<td align="right">';
   print "Sup:";
   print '</td>';
   print '<td>';
   print $sup;
   print '</td>';
   print '</tr>';
}

function case1() {
   print '<tr>';
   print '<td align="right">';
   print "Inf:";
   print '</td>';
   print '<td>';
   print $inf;
   print '</td>';
   print '</tr>';
}

switch($value) {
    case 0:
        case0();
    break;  

    case 1:
       case1();
    break;

    case 2:
      case0();
      case1(); 
    break;
}

【讨论】:

  • 不仅是解决方案,而且是开关/案例的解决方案。这样您就可以随时重复使用这些函数,而不是针对每种情况进行硬编码。
【解决方案2】:

你不能用 switch 语句来做到这一点。你可以使用这样的东西:

if ($value == 0 || $value == 2) {
    // do "zero" stuff
}
if ($value == 1 || $value == 2) {
    // do "one" stuff
}

或许:

switch ($value) {
    case 2:
    case 0:
       // do "zero" stuff
       if ($value == 0) break;
    case 1:
       // do "one" stuff
       break;
}

【讨论】:

    【解决方案3】:

    将 HTML 存储在变量中,然后在您的 switch 中使用它。

    $superiore = '<tr>
    <td align="right">
    Limite Superiore:
    </td>
    <td>'.
    $entry['lim_sup'].'CHF/100LT
    </td>
    </tr>';
    
    $inferiore = '<tr>
    <td align="right">
    Limite Inferiore:
    </td>
    <td>'.
    $entry['lim_inf'].'CHF/100LT
    </td>
    </tr>';
    
    switch($value){
        case 0:
            print $superiore;
        break;  
    
        case 1:
            print $inferiore;
        break;
    
        case 2:
            print $superiore;
            print $inferiore;
        break;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多