php中许多if else语句的替代解决方案

时间:2015-01-05 17:25:56

标签: php arrays wordpress if-statement

在我的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> ';
}
?>

现在这种方法很完美,但我知道有更好的方法来实现这一点,我相信它使用的是循环和/或关联数组。我已经调查了两者,但我担心我无法理解它,主要是因为我想要回应的,通常只依赖于一个条件。

5 个答案:

答案 0 :(得分:9)

$values = array(
    'Marketing' => 'fa-paint-brush',
    'Client Delivery' => 'fa-headphones',
    ...
);

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

答案 1 :(得分:2)

尝试为$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;
   }

答案 2 :(得分:2)

也许使用switch语句,我倾向于使用它们。亲眼看看:

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

这些工作非常棒。但是else / if

并没有错

答案 3 :(得分:0)

尝试让您的班级名称包含像mark这样的部门价值片段进行营销。修剪部门字符串并将其插入到html中。

答案 4 :(得分:0)

<?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>";
    }
}
?>