0

我正在编写一堆条件,使用 if 语句,有没有办法简化它以使其看起来更好?

$value = "1";

      if (($subvalue == 1) && ($subbucket == 1)){
        $value = "1";
      }

      if (($subvalue == 1) && ($subbucket == 2){
        $value = "1A";
      }

      if (($subvalue == 1) && ($subbucket == 3)){
        $value = "2A";
      }

      if (($subvalue == 2) && ($subbucket == 1)){
        $value = "3A";
      }

      if (($subvalue == 2) && ($subbucket == 2)){
        $value = "3B";
      }

      if (($subvalue == 2) && ($subbucket == 3)){
        $value = "3C";
      }

我发现它很乱,有没有办法重写这个?

4

3 回答 3

3

一般解决方案,如果您可以拥有任何密钥:

$lookup = array(
  1 => array(
    1 => "1",
    2 => "1A",
    3 => "2A"),
  2 => array(
    1 => "3A",
    2 => "3B",
    3 => "3C"));

$value = $lookup[$subvalue][$subbucket];
if (!$value) $value = "1";

否则,对于问题中所示的连续整数键,

$lookup = array(
  array("1", "1A", "2A"),
  array("3A", "3B", "3C"));
$value = $lookup[$subvalue - 1][$subbucket - 1];
if (!$value) $value = "1";
于 2013-09-10T01:25:30.840 回答
0

尝试,类似:

$value = '1'; $res = array('1', '1A', '2A', '3A', '3B', '3C');
for($i=0,$n=1,$q=1; $i<6; $i++,$q++){
  if($i === 3){
    $n = 2; $q = 1;
  }
  if($subvalue === $n && $subbucket === $q){
    $value = $res[$i];
  }
}
于 2013-09-10T01:46:28.803 回答
0

你会认为这是简化的吗?

$arr = array('1', '1A', '2A', '3A', '3B', '3C');
$value = $arr[($subvalue - 1) * 3 + ($subbucket - 1)];
if (!$value) $value = "1";   // steal this line from @Amadan

与@Amadan 的解决方案类似的另一个解决方案是

$arr = array( 1 => array(1 => '1', 2 => '1A', 3 => '2A'),
              2 => array(1 => '3A', 2 => '3B', 3=> '3C'));
$value = $arr[$subvalue][$subbucket];
if (!$value) $value = "1";
于 2013-09-10T01:25:20.183 回答