4

我从电子邮件表单中获取帖子值,并将所有选项值设置为数字,并尝试将它们转换为实际字符串以在电子邮件中发送。我需要让这段代码更容易使用。

if ($subject == "1") {
$sub = "General Questions"; 
} elseif($subject == "2") {
$sub = "Membership";
} elseif($subject == "3") {
    $sub = "Club Fees";
} elseif($subject == "4") {
    $sub = "Proshop & Lessons";
} elseif($subject == "5") {
    $sub = "Events"; 
} elseif($subject == "6") {
    $sub == "Leagues & Programs";
} elseif($subject == "7") {
    $sub == "Resturant & Bar";
};

也许我可以将 设置value=''为实际值并一起跳过这部分。

4

4 回答 4

8

为什么不做一个关联数组?

$subs = array(
  1 => 'General Questions',
  2 => 'Membership',
  3 => 'Club Fees',
  4 => 'Proshop & Lessons',
  // others.
);

$sub = isset($subs[$subject]) ? $subs[$subject] : 'Default Value';
于 2012-04-29T04:28:47.017 回答
4

重写的一种方法是使用switchPHP 中的语句。你可以在这里阅读更多关于它的信息

于 2012-04-29T04:27:51.187 回答
3

使用switch语句,或将潜在结果映射到它们各自的值:

switch ( $subject ) {
  case 1:
    $sub = 'foo';
    break;
  case 2:
    $sub = 'bar';
    break;
}

或者

$values = array( "Foo", "bar" );
$sub = $values[ --$subject ];
于 2012-04-29T04:28:58.840 回答
3

尝试这个

<?php
switch ($subject)
{
case "1":
  $sub = "General Questions";
  break;
case "2":
  $sub = "Membership";
  break;
case "3":
  $sub = "Club Fees";
  break;
case "4":
  $sub = "Proshop &amp; Lessons";
  break;
case "5":
  $sub = "Events";
  break;
case "6":
  $sub = "Leagues &amp; Programs";
  break;
case "6":
  $sub = "Resturant &amp; Bar";
  break;
default:
  $sub = "";
}
?>
于 2012-04-29T04:30:38.577 回答