HTML代码
0<input type="checkbox" name="count[]" id="count[]" value="0"/>
<input type="hidden" name="language[]" id="language" value="C++"/>C++
<input type="hidden" name="price[]" id="price" value="700"> <br/>
1<input type="checkbox" name="count[]" id="count[]" value="1"/>
<input type="hidden" name="language[]" id="language" value="Assembler"/>Assembler
<input type="hidden" name="price[]" id="price" value="600"><br/>
2<input type="checkbox" name="count[]" id="count[]" value="2"/>
<input type="hidden" name="language[]" id="language" value="Java"/>Java
<input type="hidden" name="price[]" id="price" value="500"> <br/>
3<input type="checkbox" name="count[]" id="count[]" value="3"/>
<input type="hidden" name="language[]" id="language" value="PHP"/>PHP
<input type="hidden" name="price[]" id="price" value="400"> <br/>
4<input type="checkbox" name="count[]" id="count[]" value="4"/>
<input type="hidden" name="language[]" id="language" value="PHP"/>PHP
<input type="hidden" name="price[]" id="price" value="400"> <br/>
<input type="submit" name="sbt" id="sbt" value="SUBMIT">
这是PHP
<?php
if(isset($_POST['sbt'])){ <br/>
$count = $_POST['count']; <br/>
$sub_menu = $_POST['sub_menu']; <br/>
$sub_price = $_POST['sub_price']; <br/>
foreach($count as $j)
echo $sub_menu[$j] . '['.$sub_price[$j]. ']' ;<br/>
}<br/>
?>
如何计算总和 - 已选中复选框的总价格?
例如:结果应显示为:
所选编程语言的总价格: C ++,Java = 1200 $
答案 0 :(得分:0)
由于价格是以数组形式提交的,因此您可以计算总计如下:
$totals = 0;
foreach ($_POST['price'] as $value) {
$totals += (int)$value;
}
echo 'Total Price of Selected Programming Languages :', implode(',', $_POST['language']), ' = ', $totals, '$';
如果您想按语言对总计进行分组:
$prices = [];
foreach ($_POST['price'] as $key => $value) {
if (empty($prices[$_POST['language']])) {
$prices[$_POST['language']] = (int)$value;
}
else {
$prices[$_POST['language']] += (int)$value;
}
}
然后你可以遍历这个新数组并按语言输出总数:
echo 'Total Price of Selected Programming Languages ';
foreach($prices as $language => $total) {
echo "{$language}: {$total}, ";
}