任何人都可以帮助我使用以下功能,为什么return
内部切换工作正常(返回正确的转换价格/数量):
function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
switch ($unit_id) {
case 8: // A Bushel
$outQ = $quantity / $lbs_in_a_bu;
$outP = $price * $lbs_in_a_bu;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 10: // Pounds
$outQ = $quantity;
$outP = $price;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 11: // CWT
$outQ = $quantity / LBS_IN_CWT;
$outP = $price * LBS_IN_CWT;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 12: // Metric Tonne
$outQ = $quantity / LBS_IN_TON;
$outP = $price * LBS_IN_TON;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 136: // W Bushel
$outQ = $quantity / $lbs_in_w_bu;
$outP = $price * $lbs_in_w_bu;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}
}
但这个不是吗? (仅返回case 136
转换后的价格/数量)(切换后无效return
)如何从上面的改进,我想用更少的代码来完成上述功能,谢谢!
function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
switch ($unit_id) {
case 8: // A Bushel
$outQ = $quantity / $lbs_in_a_bu;
$outP = $price * $lbs_in_a_bu;
case 10: // Pounds
$outQ = $quantity;
$outP = $price;
case 11: // CWT
$outQ = $quantity / LBS_IN_CWT;
$outP = $price * LBS_IN_CWT;
case 12: // Metric Tonne
$outQ = $quantity / LBS_IN_TON;
$outP = $price * LBS_IN_TON;
case 136: // W Bushel
$outQ = $quantity / $lbs_in_w_bu;
$outP = $price * $lbs_in_w_bu;
}
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}
答案 0 :(得分:3)
在每个break;
的末尾添加case
语句。否则,case
语句的下一个switch
的代码也将被执行。
您的return
语句使用switch
语句中定义的变量。如果某个$unit_id
不在case
列表中,则return
将失败。为防止return
失败,您可以在案例列表的底部添加:
default: // $unit_id not found
return ['quantity' => '0.000', 'price' => '0.000']; // whatever you like
或者你可以抛出异常。
答案 1 :(得分:2)
返回退出函数,所以在你的情况下作为一个休息,这就是它在第一种情况下工作的原因。