2012-12-19 109 views
0

下面的代码的显示订购的产品个体重量:萨姆PHP数组

$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'].'   '; 

} 

这显示了每个订购产品的wieght。我被卡住的是而不是显示单独的重量,我需要显示一个总重量。例如,如果产品被勒令三次,它的重量7千克,此刻的代码表明:

Product     7.00 7.00 7.00 

我将如何使其显示总重量,21公斤?

+0

在这种情况下,你不能流数据。在将所有数据汇总之前,您必须迭代所有数据。 – ComFreek

+7

让我们来看看,我有一个**数组**,并且我希望其中的项**的总和**。现在,什么可能会这样一个函数被称为... – DaveRandom

+2

@DaveRandom - 让他只是让他摆脱他的痛苦..... [array_sum()](http://php.net/manual/en/function.array -sum.php) – SDC

回答

3

使用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

我试过了,为什么我会问这个问题?我得到一个错误,在结果 – user1879415

+0

@ user1879415可能是因为你的数组包含'字符串'而不是'整数'或'浮动'? – Peon

+0

也许对给定的代码的解释可能有助于 – user1879415

0

只需设置一个计数器为0,循环之前,并添加循环中做到这一点,是这样的:那么

$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'].'&nbsp;&nbsp;&nbsp;'; 
      $total += $weight['products_weight']; 
     } 

} 

变量$总应该返回21

0

如果您已通过ID选择产品,最简单的解决方案是将行数乘以重量。无需将其放入数组中。

0
$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'] 

谢谢你的帮助(!)