2015-04-06 199 views
1

有没有写这个的没有更好的办法:更好的方式,如果else语句

if (in_array('WIN_WAITING', $statuses)) { 
    $this->globalStatus = 'WIN_WAITING'; 
} else if (in_array('IN_PLAY', $statuses)) { 
    $this->globalStatus = 'IN_PLAY'; 
} else if (in_array('WON', $statuses)) { 
    $this->pay($this->tickets['ticketID']); 
    $this->globalStatus = 'WON'; 
} else if (in_array('PAYEDOUT', $statuses)) { 
    $this->globalStatus = 'PAYEDOUT'; 
} else if (in_array('CLOSED', $statuses)) { 
    $this->globalStatus = 'CLOSED'; 
} else if (in_array('LOST', $statuses)) { 
    $this->globalStatus = 'LOST'; 
} else if (in_array('OPEN', $statuses)) { 
    $this->globalStatus = 'OPEN'; 
} 
+1

您可以通过将'pin'存储在'array'中并使用'foreach'循环来减少'if'' else – 2015-04-06 13:38:05

+1

另外:'PAYEDOUT'应该是'PAIDOUT' - 另一个不错的英语拼写规则! – halfer 2015-04-06 13:38:49

回答

3

这应该为你工作:通过所有的搜索字符串,如果

(这里我只环路我发现我跳出循环)

<?php 

    $search = ["WIN_WAITING", "IN_PLAY", "WON", "PAYEDOUT", "CLOSED", "LOST", "OPEN"]; 

    foreach($search as $v) { 
     if(in_array($v, $statuses)) { 
      if($v == "WON") $this->pay($this->tickets['ticketID']); 
      $this->globalStatus = $v; 
      break; 
     } 

    } 

?> 
+0

你忘了'WON'的条件;) – 2015-04-06 13:38:54

+0

@AkramFares感谢您的通知,更新了我的回答 – Rizier123 2015-04-06 13:40:11

+0

@AkramFares:我认为这可以留给OP':-)' – halfer 2015-04-06 13:40:14

2

也许像

$options = array('WIN_WAITING', 'IN_PLAY', 'WON', 'PAYEDOUT', 'CLOSED', 'LOST', 'OPEN'); 

for($i=0; $i<=7; $i++) { 

if(in_array($options[$i], $statuses)) { 
    $this->globalStatus = $options[$i]; 
    break; 
} 

} 

未测试,只是一个想法