2015-12-20 116 views
1

所以首先关闭,这里是代码:简化嵌套的If ... Else语句;柔性阵列

$greens = $_REQUEST['greens']; 
    $squash = $_REQUEST['squash']; 
    $tomatoes = $_REQUEST['tomatoes']; 

    $single = $greens xor $squash xor $tomatoes; 


    if (isset($greens,$squash,$tomatoes)) { 

    $array = [$greens,$squash,$tomatoes]; 
    $product = implode(', ',$array); 

    } else if (isset($greens,$squash)) { 

    $array = [$greens,$squash]; 
    $product = implode(', ',$array); 

    } else if (isset($greens,$tomatoes)) { 

    $array = [$greens,$tomatoes]; 
    $product = implode(', ',$array); 

    } else if (isset($squash,$tomatoes)) { 

    $array = [$squash,$tomatoes]; 
    $product = implode(', ',$array); 

    } else if (isset($single)) { 

    $product = $single; 

    } else { 

    $product = $_REQUEST['vendor_product']; 

    } 

这是一个PHP文件提交供应商登记表格的一部分。如果供应商选择“生产”作为他们的产品类型,则出现一组复选框选项,并且需要选择至少一个选项。根据选项集的不同,所选值将在一个字段中集中提交到数据库中。如何在数据库中查看它们的示例如下:'Greens, Squash & Zucchini','Greens, Squash & Zucchini, Tomatoes''Greens'等,其中', '被插入,如果选择了多个选项。

上面的代码工作,但想知道是否有一种方法来简化这一点,因为我很可能会添加更多的选项供用户选择。此外,即使每个条件都有多个真实结果,三元运算符仍可以使用吗?我对理解这个操作符还是比较陌生的。

+0

'php's'数组的设计灵活。 –

回答

2
$names = ['greens', 'squash', 'tomatoes']; 

$array = []; 
foreach ($names as $name) { 
    if (isset($_REQUEST[$name])) { 
     $array[] = $_REQUEST[$name]; 
    } 
} 

$product = implode(', ',$array); 

if (count($array) == 0) { 
    $product = $_REQUEST['vendor_product']; 
} 
+0

给自己的提示:在问这些问题之前查看控制结构:p谢谢 – tylerptmusic

0

简化此代码并使其更加灵活的最佳方法是同时更改窗体本身并使用数组。

而不是

<input type="checkbox" name="green" value="Greens" /> 
<input type="checkbox" name="squash" value="Squash & Zucchini" /> 
<input type="checkbox" name="tomatoes" value="Tomatoes" /> 

您将有

<input type="checkbox" name="produce[]" value="Greens" /> 
<input type="checkbox" name="produce[]" value="Squash & Zucchini" /> 
<input type="checkbox" name="produce[]" value="Tomatoes" /> 

而且PHP代码:

if (empty($_REQUEST['produce'])) { 
    $product = $_REQUEST['vendor_product']; 
} else { 
    $product = implode(', ', $_REQUEST['produce']); 
} 

或三元运算符:

$product = empty($_REQUEST['produce']) ? implode(', ', $_REQUEST['produce']) : $_REQUEST['vendor_product'];