2016-07-25 6 views
0

enter image description here利用状況PHPでロジックを計算する

これはmysqlのクエリ結果です。今度は、チャレンジ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には、目的の出力が含まれているはずです。テストされていない。

関連する問題