php 中大量 ifelse 语句的替代解决方案

The alternative solution to lots of ifelse statements in php

在我的 wordpress 网站中,如果自定义字段与特定字符串匹配,我会显示一个特定的 (fontawesome) 图标。这是相关代码:

<?php $department = get_field('department'); ?>     

<?php 
if($department == "Marketing"){ echo '<i class="fa fa-paint-brush fw fa-lg"></i> ';
} elseif($department == "Client Delivery"){echo '<i class="fa fa-headphones fa-lg"></i> ';
} elseif($department == "Implementation"){echo '<i class="fa fa-gears fw fa-lg"></i> ';
} elseif($department == "Sales"){echo '<i class="fa fa-money fw fa-lg"></i> ';
} elseif($department == "Executive"){echo '<i class="fa fa-building-o fw fa-lg"></i> ';
} elseif($department == "IT"){echo '<i class="fa fa-laptop fw fa-lg"></i> ';
}
?>

现在这很完美,但我只知道有更好的方法来实现这一点,我相信它正在使用一个循环 and/or 一个关联数组。我已经研究了两者,但恐怕我无法理解它,主要是因为我想要回应的内容通常只依赖于一个条件。

尝试为您的 $department 使用 switch statement

  switch ($department) {
    case 0:
        echo "$department equals 0";
        break;
    case 1:
        echo "$department equals 1";
        break;
    case 2:
        echo "$department equals 2";
        break;
   }
$values = array(
    'Marketing' => 'fa-paint-brush',
    'Client Delivery' => 'fa-headphones',
    ...
);

echo '<i class="fa ' . $values[$department]. ' fw fa-lg"></i> ';

也许使用switch语句,我倾向于使用那些。自己看看:

    switch($department) {
          case "Marketing":
              echo "foo";
              break;
          case "Client Delivery":
              echo "bar";
              break
          default:
              echo "Not found";
    }

而且这些效果非常好。但是 else/if

没什么问题

尝试让您的 class 名称包含部门价值的片段,例如 mark 用于市场营销。 Trim 部门字符串并将其插入 html。

<?php $department = get_field('department'); ?>     

<?php 
switch(strtolower($department)) {
    case "marketing" : {
        echo '<i class="fa fa-paint-brush fw fa-lg"></i> ';
        break;
    }
    case "client delivery" : {
        echo '<i class="fa fa-headphones fa-lg"></i> ';
        break;
    }
    // ... finish all of your cases
    default : {
        echo "<font color='red'>Unknown department received : " .  $department ."</font>";
    }
}
?>