2016-05-09 88 views
2

我有一個產品列表(包括種類和數量)如何按類別從產品列表中得到總和組

$html = ""; 
foreach ($products as $product) { 
    $html .= $product->category; 
    $html .= $product->name; 
    $html .= $product->quantity; 
} 
echo $html; 

關注該列表

Category | Product | Quantity 
Timsum  T1   10 
Timsum  T2   20 
Timsum  T3   30 
Sauces  S1   5 
Sauces  S2   15 

如何總結組和顯示最近每行類別

Category | Product | Quantity 
Timsum  T1   10 
Timsum  T2   20 
Timsum  T3   30 
**Sum Timsum   60**  
Sauces  S1   5 
Sauces  S2   15 
**Sum Sauces   20** 
+0

的類別始終?或者可以像Timsum,Sauces,Timsum這樣的事情發生? – Webeng

+0

格式按類別排序,如Timsum,醬,雞,... –

+0

你試過我的答案? – Webeng

回答

1

添加$sum變量記錄積累的數量,使一些條件語句時,該類別已經轉移應該做的工作,以追蹤:爲了

$html = ""; 
$first_iteration = FALSE; 
$sum = 0; 

foreach ($products as $product) { 

    if (!$first_iteration) 
    { 
     $first_iteration = TRUE; 
     $temp_category = $product->category; 
    } 

    if ($temp_category != $product->category) 
    { 
     html .= "**".$temp_category; 
     html .= $sum; 
     $sum = 0; 
     $temp_category = $product->category; 
    } 

    $html .= $product->category; 
    $html .= $product->name; 
    $html .= $product->quantity; 

    $sum += (integer) $product->quantity; 
} 
html .= "**".$temp_category; 
html .= $sum; 

echo $html; 
1

訂購結果按類別名稱設置,然後使用臨時變量:

$qty = 0; 
$last_cat = null; 

foreach ($products as $product) { 
    if ($product->category != $last_cat && $last_cat) { 
    echo "**Sum $last_cat $qty\n"; 
    $qty = 0; 
    $last_cat = $product->category; 
    } 

    printf("%s\t%s\t%s\n", 
    $product->category, $product->name, $product->quantity); 

    $last_cat = $product->category; 
    $qty += $product->quantity; 
} 
相關問題