2 回答
TA贡献1810条经验 获得超4个赞
有很多方法可以做到这一点
使用 if-else:
$payment_mode = "bank";
if($payment_mode == "cod")
$selected_payment_option = "Cash on Delivery";
elseif($payment_mode == "stripe")
$selected_payment_option = "Stripe";
elseif($payment_mode == "bank")
$selected_payment_option = "Bank";
else
$selected_payment_option = "your default value";
print($selected_payment_option)
// output: Bank
使用开关:
$payment_mode = "cash";
switch($payment_mode) {
case "cod": $selected_payment_option = "Cash on Delivery"; break;
case "stripe": $selected_payment_option = "Stripe"; break;
case "bank": $selected_payment_option = "Bank"; break;
default: $selected_payment_option = "your default value";
}
print($selected_payment_option);
// output: your default value
使用三元运算符:
$payment_mode = "stripe";
$selected_payment_option = $payment_mode == "cod" ? "Cash on Delivery "
: ($payment_mode == "stripe" ? "Stripe" : ($payment_mode == "bank" ? "Bank"
: "your default value"));
print($selected_payment_option);
// output: Stripe
使用逻辑运算符:
$payment_mode = "bank";
$selected_payment_option = "your default value";
$payment_mode == "cod" && ($selected_payment_option = "Cash on Delivery") ||
$payment_mode == "stripe" && ($selected_payment_option = "Stripe") ||
$payment_mode == "bank" && ($selected_payment_option = "Bank");
print($selected_payment_option);
// output: Bank
使用关联数组:
$payment_modes = array("cod"=> "Cash on Delivery", "stripe"=> "Stripe", "bank" => "Bank");
$payment_mode = "cod";
$selected_payment_option = array_key_exists($payment_mode, $payment_modes) ?
$payment_modes[$payment_mode] : "your default value";
print($selected_payment_option);
// output: Cash on Delivery
TA贡献1829条经验 获得超9个赞
请为此类代码使用开关。它还具有捕获 $payment_mode 未设置值的情况的好处。
function getPaymentOption($payment_mode) {
switch ($payment_mode) {
case "cod":
return "Cash on Delivery";
break;
case "stripe":
return "Stripe";
break;
case "bank":
return "Bank";
break;
default:
return "unknown";
}
}
像这样使用:
$selected_payment_option = getPaymentOption($payment_mode);
- 2 回答
- 0 关注
- 93 浏览
添加回答
举报