开发者

php - calculate price multiplied by quantity for several items to get individual totals and a grand total

I have a form that has 7 different items. The user will be able to input quantity (unlimited) and the price will be set for each item (let's say for example, item 1 is $18, and item 2 is $20, etc.). What I have done with another form that's almost identical is this:

if(!empty($_POST[qty_item_1])) {
    $total_1 = ($_POST[qty_item_1] * 18);
} else {
$total_1 = "0";
}

if(!empty($_POST[qty_item_2])) {
$total_2 = ($_POST[qty_item_2] * 20);
} else {
$total_2 = "0";
}

I would have a code block like those for each item. It seems to work fine but I feel like this开发者_如何转开发 is probably the hard way to do it but I'm having trouble figuring out what else I might do. Any suggestions?


Given your field names, you could do something like:

$totals = array();
for ($i = 1; $i <= 7; $i++) {
    $total[$i] = isset($_POST["qty_item_{$i}"]) ? intval($_POST["qty_item_{$i}"]) : 0;
}

The other option is to simply name your fields qty_item[]. When PHP parses the submitted data, it'll convert all those qty_item fields into an array for you. You'd still need to post-process to make sure that they contain valid numbers and whatnot, thoguh.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜