if elseif else太多怎么办
写了一个函数,if elseif else太多,很不漂亮,有没有好的办法优化。主要是判断$child,$mother,$father三个值,每个参数可能有四个值11,10,01,00
,第一个参数$child必需的,其它两个可选,计算每一种的组合,根据不同的组合,返回一个不同的$allele值。
如$child=00,$mother空值,$father空值,返回 "Unknown"
$child=11, $mother= 10, $father空值, 返回"Both (Homozygous)"
谢谢,新手只能写成这样难看的代码。
<?php
function getAllele($child,$mother = '',$father = '')
{
//only child data
if(empty ($mother) && empty ($father)){
if($child == '11'){
$allele = 'Both (Homozygous)';
}else{
$allele = 'Unknown';
}
return $allele;
//child and mother data
}elseif(!empty ($mother) && empty ($father)){
if($child == "11"){
$allele = 'Both (Homozygous)';
}elseif ($child == '01' or $child == '10'){
if($mother == '11'){
$allele = 'Maternal (inferred)';
}elseif ($mother == '00'){
$allele = 'Paternal (inferred)';
}else{
$allele = 'Unknown';
}
}else{
$allele = 'Unknown';
}
return $allele;
//child and father data
}elseif(empty ($mother) && !empty ($father)){
if($child == "11"){
$allele = 'Both (Homozygous)';
}elseif ($child == '01' or $child == '10'){
if($father == '11'){
$allele = 'Paternal (inferred)';
}elseif ($father == '00'){
$allele = 'Maternal (inferred)';
}else{
$allele = 'Unknown';
}
}else{
$allele = 'Unknown';
}
return $allele;
//child and parents data
}elseif(!empty ($mother) && !empty ($father)){
if($child == "11"){
$allele = 'Both (Homozygous)';
}elseif ($child == '01' or $child == '10'){
if($mother == '11'){
if($father == '01' or $father = '10' or $father == '00'){
$allele = 'Maternal (confirmed)';
}else{
$allele = 'Unknown';
}
}elseif($mother == '01' or $mother == '10'){
if($father== "00"){
$allele = 'Maternal (confirmed)';
}elseif($father=='11'){
$allele = 'Paternal (confirmed)';
}else{
$allele = 'Unknown';
}
}elseif ($mother == '00'){
if($father == '10' or $father == '01' or $father == '11'){
$allele = 'Paternal (confirmed)';
}else{
$allele = 'Unknown';
}
}
}else{
$allele = 'Unknown';
}
return $allele;
}
}
//end
?> 逆向思维:
结果的状态集 相比于 if-else条件集小很多,可画一个状态机。
一个输出对应于有哪些条件集,条件集是否有合并的余地?
另:一个输出对应一组条件,针对这个输出写一个函数。如果有N个输出,就写N个函数。会清晰一些。 本帖最后由 chlinux 于 2013-02-18 17:55 编辑
回复 1# feiyue0908
可考虑把数据写到一个数组里。可多维array(
'child'=>array(11,10,01,00),
'mother'=>array(11,10,01,00),
'father'=>array(11,10,01,00),
)
//然后
foreach ($array as $key => $value) {
//
} 谢谢,我试试吧,对复杂程序还是比较迷茫的,查查资料看看
回复 2# chlinux
switch/case bikong0411 发表于 2013-02-19 02:19 static/image/common/back.gif
switch/case谢谢,我试试查查资料看看 能用表格驱动的不要用if else 你说的表格驱动是什么样的?谢谢
回复 6# yyxxzz
回复 7# feiyue0908
<代码大全2> 表格驱动 google 一下 switch