2016-07-25 115 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現在應該包含您想要的輸出。未經測試。