2016-07-25 59 views
0

enter image description here可用性计算php中的逻辑

这是一个mysql查询结果。现在我必须根据每个challan ID计算php中的可用数量。预期的结果将是:

ChallanId | Avaiable Qty | unitCostPrice | totalPrice  
    11  | 7   |  2   | 14   
    12  | 10   |  1   | 10 

它如何在PHP中完成?使用foreach或任何其他技巧。

+1

你能告诉我们你已经尝试了什么? – zhon

回答

2

我会做一个更聪明的查询在SQL中的计算。

select 
    ChallanId, 
    UnitCostPrice, 
    sum(`ItemIn`)-sum(`ItemOut`) as AvailableQty, 
    (sum(`ItemIn`)-sum(`ItemOut`))*UnitCostPrice as totalPrice 
from tbl 
group by ChallanId 

Live demo

3

虽然要达到这一目的PHP解决方案,但在这里我想SQL查询也可以这样做:

select 
    ChallanId, 
    sum(case when Narration = 'in' then ItemIn when Narration = 'out' then 0 - ItemOut end) as Avaiable_Qty, 
    unitCostPrice, 
    sum(case when Narration = 'in' then ItemIn when Narration = 'out' then 0 - ItemOut end) * unitCostPrice as totalPrice 
from (your query here...) 
having Avaiable_Qty > 0 
group by ChallanId 
0

这是怎么样的,因为你没有分享你的PHP实现伪码。

首先,您可以从ItemIn或ItemOut是否不为零开始进行叙述,事实上,这样做可能会更好,因为您可以在同一行中引入项目和项目。但这不是问题。

$output = array(); 
foreach ($dbResults as $row) { 
    // Create an output entry 
    if (!array_key_exists($row['ChallanID'], $output)) { 
     $output[$row['ChallanID']] = array('Qty' => 0, 'CostPrice' => 0, 'Total' => 0); 
    } 

    // Add to totals 
    $output[$row['ChallanID']]['Qty'] += ($row['ItemIn'] - $row['ItemOut']); 
    $output[$row['ChallanID']]['CostPrice'] = $row['UnitCostPrice']; // you may want to average this instead? 
    $output[$row['ChallanID']]['Total'] += $output[$row['ChallanID']]['Qty'] * $output[$row['ChallanID']]['CostPrice']; 
} 

$output现在应该包含您想要的输出。未经测试。