我对任何编码都很新,所以如果这看起来很基本,请耐心等待。嵌套如果/否则在PHP
我想在电子邮件中用变量$ fname分配合适的问候语。名称值源自的数据是简单的单个字符串。格式的可能变化因此很多。
在这个特定的应用程序,细节大多写成之一:
-Mr约翰·史密斯
-Mr史密斯
- 约翰·史密斯
-John
因此,我需要评估方法用于输入名称,然后才能将其分配给变量。
我写了下面的代码,但在线检查抛出了“一个意想不到的'else'”。
这一切似乎对我来说,我看过的在线示例似乎遵循类似的顺序。
任何帮助非常感谢!
谢谢,
Rob。
确定 - 再次使用正确,实际测试的工作代码进行编辑。 (我昨天累了,错过了一个可能的结果)这绝对适用于我需要的所有排列组合。希望它能帮我节省一些其他初学者的时间,让我做这么简单的事情!
再次感谢所有帮助过我的人,并为我的“新手”道歉。
<?php
$saltest = explode(" ", $client);
if (empty($saltest[1])) { // checks to see if it a single name eg 'John'.
$fname = $saltest[0];
} elseif (isset($saltest[1])) { // if it is not a single word, checks to see if starts with a salutation
switch ($saltest[0]) {
case 'Mr';
case 'Mrs';
case 'Ms';
case 'Mr.';
case 'Mrs.';
case 'Ms.';
case 'Dr';
case 'Dr.';
$withsal = $saltest; // if it does, allocate the array to variable $withsal.
break;
default: $withoutsal = $saltest; // if it doesn't - allocate it to variable $withoutsal.
break;
}
}
if (isset($withoutsal)) { // if already established that there is no salutation, issue the $fname & $lname variables
$fname = $withoutsal[0];
$lname = $withoutsal[1];
} elseif (isset($withsal) and isset($withsal[2])) { // if it has a salutation and is compised of 3 words - issue $fname & $lname accordingly.
$fname = $withsal[1];
$lname = $withsal[2];
} elseif (isset($withsal) and isset($withsal[1])) { // if it has a salutation but is only 2 words, put them together to create variable $fname eg. "Mr Smith" and declare the $lname variable as NULL. It is not needed.
$fname = implode(" ", $withsal);
$lname = NULL;
}
echo $fname;
?>
'如果{...}否则{...}否则{...}',当将第三块被执行? – Biffen 2015-03-02 15:27:04
您需要在您的else语句中添加表达式:'elseif(expression)'... – vim 2015-03-02 15:27:36
添加右括号,否则您的关闭。 – Pinu 2015-03-02 15:34:13