Problem: Find the sum of the values in 'subtotal' for each 'id' and store the respective sum for each id in an array (or variables).
My sloppy solution at the moment is to run a foreach with multiple if statements inside that count the occurrences. This is adequate for something like 5 ids, but I have to iterate this over 38 ids. I would like to store the results sequentially in an array if possible.
How can I make it more efficient? Any and all help will be appreciated. (See my sloppy solution at the end of this for a good chuckle)
Desired Result:
- sum of all ID 1 = 10
- sum of all ID 2 = 18
- sum of all ID 3 = 14
- sum of all ID 4 = 4
- sum of all ID 5 = 3
Array Code for Manipulation
$someArray = array(
array(
'id'=> 1,
'subtotal'=> 5),
array(
'id'=> 1,
'subtotal'=> 5),
array(
'id'=> 2,
'subtotal'=> 6),
array(
'id'=> 2,
'subtotal'=> 6),
array(
'id'=> 2,
'subtotal'=> 6),
array(
'id'=> 3,
'subtotal'=> 7),
array(
'id'=> 3,
'subtotal'=> 7),
array(
'id'=> 4,
'subtotal'=> 2),
array(
'id'=> 4,
'subtotal'=> 2),
array(
'id'=> 5,
'subtotal'=> 3),
);
Sloppy Solution
$sum_id_1 = 0;
$sum_id_2 = 0;
$sum_id_3 = 0;
$sum_id_4 = 0;
$sum_id_5 = 0;
foreach ($someArray as $k) {
if ($k['id'] == 1) {
$sum_id_1 += $k['subtotal'];
}
if ($k['id'] == 2) {
$sum_id_2 += $k['subtotal'];
}
if ($k['id'] == 3) {
$sum_id_3 += $k['subtotal'];
}
if ($k['id'] == 4) {
$sum_id_4 += $k['subtotal'];
}
if ($k['id'] == 5) {
$sum_id_5 += $k['subtotal'];
}
}
Sloppy Solution Output (on echo)
- 10
- 18
- 14
- 4
- 3