所以首先關閉,這裏是代碼:簡化嵌套的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'
等,其中', '
被插入,如果選擇了多個選項。
上面的代碼工作,但想知道是否有一種方法來簡化這一點,因爲我很可能會添加更多的選項供用戶選擇。此外,即使每個條件都有多個真實結果,三元運算符仍可以使用嗎?我對理解這個操作符還是比較陌生的。
'php's'數組的設計靈活。 –