谁能帮我完成以下功能,为什么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, '.', '')];
}发布于 2017-06-05 19:20:35
在每个break;语句的末尾添加case语句。否则,switch语句的下一个switch的代码也将被执行。return语句使用在switch语句中定义的变量。如果$unit_id没有出现在case的列表中,那么return就会出错。为了防止return失败,可以在案例列表的底部添加以下内容:
default: // $unit_id not found
return ['quantity' => '0.000', 'price' => '0.000']; // whatever you like或者你可以抛出一个例外。
发布于 2017-06-05 19:22:08
返回退出函数,因此在您的情况下充当中断,这就是它在第一种情况下工作的原因。
https://stackoverflow.com/questions/44376147
复制相似问题