if语句,具有x^2个可能性,与响应匹配,可选字段


if statements, with x^2 possbilities, matching to a response, optional fields

如果有人能为这个问题想出一个更好的名字,请编辑:)

我有四个字段,它们都是可选的,在PHP环境中工作,尽管这个问题可能与任何语言有关。

如果设置了它们,则会将它们发送到服务器并做出响应。我需要将响应ID与字段相匹配。

字段:A.BCD

响应阵列:0,1,2,3

如果一切都准备好了,那就很容易了。我可以按原样匹配它们,A0、B1、C2、D3。如果只设置了C和D,我得到C0,D1。如果设置了A、B和D,则为A0、B1、D2。

要对此进行编码,我必须执行以下操作:

if($a, $b, $c, $d) { $a = $response[0]; $b = $response[1]; $c = $response[2]; $d = $response[3]; }
elseif($a, $b, $d) { $a = $response[0]; $b = $response[1]; $d = $response[2]; }
elseif($a, $d) { $a = $response[0]; $d = $response[1]; }

每个可能性为16。如果我有8个字段,就会有64个If语句。

有没有一种方法可以在不必编写x^2 if语句的情况下匹配设置为响应数组的字段?

非常感谢,如果你需要我澄清,请告诉我。

以某种方式获取数组中的$a$b等;我想它们最初是作为数组提交的。假设你有一个数组,比如:

$letters = array('a', 'c');

然后简单地说:

$result = array_combine($letters, array_slice($response, 0, count($letters)));

您可以使用for循环在fileds上迭代,使用外循环迭代(2^n)次。

在试运行后,我编写了如下代码:

$fields = array("A","B","C","D".....m values)
$response_array_size = sizeof($fields) //size
for ($i = 0; $i < pow(2,$response_array_size); $i++) {
    for ($j = 0, $k = 0; j < $response_array-size; $j++) {
        if (isset( $fields[$j] ) {
           $set_fields[$k] = $response[$j];
           $k++;
        }
    /* do whatever with set_fileds
       set_fileds contains only the fields which were set
    */ 
    }
}

时间复杂性:n^2