[英]Need help on loop in php to sum by group
我需要以下幫助。 需要將我的類別與金額分組,然后將總金額排在底部。 並計算每個類別的百分比
echo print_r($results);
Array
(
[0] => stdClass Object
(
[expense_category] => Salary
[expense_amount] => 100
)
[1] => stdClass Object
(
[expense_category] => Electricity
[expense_amount] => 30
)
[2] => stdClass Object
(
[expense_category] => Gas
[expense_amount] => 15
)
[3] => stdClass Object
(
[expense_category] => Gas
[expense_amount] => 10
)
)
我正在嘗試獲得以下輸出:
+--------------------------+--------------+----------+
|Expense Category|cat_count|Expense Amount|Percentage|
+--------------------------+--------------+----------+
|Salary |1 |100 |65% |
|Electricity |1 |30 |19% |
|Gas |2 |25 |16% |
+----------------+---------+--------------+----------+
|TOTAL |4 |155 |100% |
+----------------+---------+--------------+----------+
需要以下幫助:
<table>
<tr>
<th>Expense Category</th>
<th>cat_count</th>
<th>Expense Amount</th>
<th>Percentage</th>
</tr>
<tr>
<td><?php echo $category ?></td>
<td><?php echo $cat_count ?></td>
<td><?php echo $amount ?></td>
<td><?php echo $percent ?></td>
</tr>
<tr>
<th>TOTAL</th>
<th><?php echo $Count_Sum; ?></th>
<th><?php echo $Cat_Sum; ?></th>
<th>100%</th>
</tr>
</table>
在這里,答案帶有注釋...
<?php
$results = [
"0" => (object)
array (
"expense_category" => "Salary",
"expense_amount" => 100
),
"1" => (object)
array (
"expense_category" => "Electricity",
"expense_amount" => 30
),
"2" => (object)
array (
"expense_category" => "Gas",
"expense_amount" => 15
),
"3" => (object)
array (
"expense_category" => "Gas",
"expense_amount" => 10
)
];
foreach($results as $object){
$cat = $object->expense_category;
// initialize
// null coalescer ?? requires PHP >= 7
$cat_count[$cat] = $cat_count[$cat] ?? 0;
$amount [$cat] = $amount [$cat] ?? 0;
// increment
$cat_count[$cat]++;
// sum
$amount[$cat] += $object->expense_amount;
}
$amount['total'] = array_sum($amount);
// print_r($results);
?>
<table>
<tr>
<th>Expense Category</th>
<th>cat_count</th>
<th>Expense Amount</th>
<th>Percentage</th>
</tr>
<?php
foreach($cat_count as $cat => $count){
$percent = $amount[$cat] / $amount['total'];
$percent = round($percent * 100);
echo "
<tr>
<td>$cat</td>
<td>$count</td>
<td>{$amount[$cat]}</td>
<td>$percent</td>
</tr>
";
}
?>
<tr>
<th>TOTAL</th>
<th><?php echo array_sum($cat_count); ?></th>
<th><?php echo $amount['total']; ?></th>
<th>100%</th>
</tr>
</table>
<table> <tr> <th>Expense Category</th> <th>cat_count</th> <th>Expense Amount</th> <th>Percentage</th> </tr> <tr> <td>Salary</td> <td>1</td> <td>100</td> <td>65</td> </tr> <tr> <td>Electricity</td> <td>1</td> <td>30</td> <td>19</td> </tr> <tr> <td>Gas</td> <td>2</td> <td>25</td> <td>16</td> </tr> <tr> <th>TOTAL</th> <th>4</th> <th>155</th> <th>100%</th> </tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.