以下代码显示订购产品的单个重量:
$weightsql = 'select op.products_name,
op.products_quantity,
p.products_weight
from ' . TABLE_ORDERS_PRODUCTS . ' op
left join ' . TABLE_PRODUCTS . ' p on op.products_id = p.products_id
where op.products_id = ' . $pro['products_id'];
$weightq = tep_db_query( $weightsql );
while ($weight = tep_db_fetch_array( $weightq )) {
if ($category_parent_id != 0)
$list_items[] = $weight['products_weight'] . ' ';
}
这显示了订购的每种产品的重量。我所坚持的是,我需要显示总重量,而不是显示单独的重量。例如,如果该产品被订购了 3 次,重量为 7 公斤,则此时的代码显示:
Product 7.00 7.00 7.00
如何让它显示总重量,21公斤?
array_sum()
array_sum() examples
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
The above example will output:
sum(a) = 20
sum(b) = 6.9
只需在循环之前将计数器设置为 0 并在循环期间添加 do it,如下所示:
$total = 0;
$weightsql = 'select op.products_name, op.products_quantity , p.products_weight from ' . TABLE_ORDERS_PRODUCTS . ' op left join ' . TABLE_PRODUCTS . ' p on op.products_id = p.products_id where op.products_id = '.$pro['products_id'];
$weightq = tep_db_query( $weightsql );
while ($weight = tep_db_fetch_array( $weightq )){
if($category_parent_id != 0) {
$list_items[] = $weight['products_weight'].' ';
$total += $weight['products_weight'];
}
}
变量 $total 应返回 21。
如果您通过 ID 选择产品,最简单的解决方案是将行数乘以重量。无需将其放入数组中。
$weightsql = 'select op.products_name, sum(op.products_quantity * p.products_weight) as weightsum from ' . TABLE_ORDERS_PRODUCTS . ' op left join ' . TABLE_PRODUCTS . ' p on op.products_id = p.products_id where op.products_id = '.$pro['products_id'];
echo $weight['weightsum']
感谢您的帮助(!)