Need help on loop in PHP to sum total and group by

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
 )
)


I'm trying to get the output below:
+--------------------------+--------------+----------+
|Expense Category|cat_count|Expense Amount|Percentage|
+--------------------------+--------------+----------+
|Salary          |1        |100           |65%       |
|Electricity     |1        |30            |19%       |
|Gas             |2        |25            |16%       |
+----------------+---------+--------------+----------+
|TOTAL           |4        |155           |100%      |
+----------------+---------+--------------+----------+

Need help with below:
<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>

Ok, I got it in one way…

<?php
// Get the sum
$group = array();
foreach($results as $r){
  $group[$r->expense_category] = $group[$r->expense_category] + $r->expense_amount;
}

// Display
foreach($group as $expense_category=>$expense_amount){
?>
  <tr>
   <td style="text-align:left;"><?php echo $expense_category; ?></td>
   <td style="text-align:right;"><?php $percentage = ($expense_amount / $sum) * 100; echo round($percentage,2); ?>%</td>
   <td style="text-align:right;"><?php echo format_currency($expense_amount); ?></td>
  </tr>
<?php } ?>