I have an array of objects which I am trying to condense in php. This is my array
$proposedStudentFeeCollection = [{"id":1,"student_id":"1","feeType_id":"2","proposed_fee":"5000"},
{"id":2,"student_id":"1","feeType_id":"1","proposed_fee":"5000"},
{"id":3,"student_id":"1","feeType_id":"1","proposed_fee":"2000"},
{"id":4,"student_id":"1","feeType_id":"2","proposed_fee":"15000"},
{"id":5,"student_id":"1","feeType_id":"2","proposed_fee":"5000"},
{"id":6,"student_id":"1","feeType_id":"11","proposed_fee":"9000"},
{"id":7,"student_id":"1","feeType_id":"1","proposed_fee":"20000"},
{"id":8,"student_id":"1","feeType_id":"16","proposed_fee":"1000"}]
I want to get a "new" simplified array which gives me sum of same feeType_id
like so
[{"id":1,"student_id":"1","feetype_id":"1","proposed_fee":"27000"},
{"id":2,"student_id":"1","feetype_id":"2","proposed_fee":"25000"},
{"id":3,"student_id":"1","feetype_id":"11","proposed_fee":"9000"},
{"id":4,"student_id":"1","feetype_id":"16","proposed_fee":"1000"}]
I am trying to do it like so
$myArray = array();
for($i=0; $i<2; $i++){
$tempObject = $proposedStudentFeeCollection[$i];
for($j=count($proposedStudentFeeCollection)-1; $j >= 0; $j--) {
if($tempObject->feetype_id == $proposedStudentFeeCollection[$j]->feetype_id){
$tempObject->proposed_fee += $proposedStudentFeeCollection[$j]->proposed_fee;
unset($proposedStudentFeeCollection[$j]);
}
}
$myArray[] = $tempObject;
}
return $myArray;
But I am not getting the answer. What is the correct way?
Create an associative array that uses the column that you want to group by as a key. Loop over the original array, and add the row if it doesn't already exist in the result, otherwise just add to the total proposed_fee
.
$totals = [];
foreach ($proposedStudentFeeCollection as $e) {
$id = $e['feeType_id'];
if (isset($totals[$id])) {
$totals[$id]['proposed_fee'] += $e['proposed_fee'];
} else {
$totals[$id] = $e;
}
}
A simple foreach is all you need. You have to create an element for each feeType_id and then just add up all fees.
$id = 1;
$fees = [];
foreach ($proposedStudentFeeCollection as $data) {
$feeTypeID = $data->feeType_id;
if (!isset($fees[$feeTypeID])) {
$fees[$feeTypeID] = new stdClass;
$fees[$feeTypeID]->id = $id;
$fees[$feeTypeID]->proposed_fee = 0;
$fees[$feeTypeID]->student_id = $data->student_id;
$fees[$feeTypeID]->feeType_id = $data->feeType_id;
$id++;
}
$fees[$feeTypeID]->proposed_fee += $data->proposed_fee;
}
//$fees = array_values($fees);
If you dont want the fee type ids as the array keys, just use array_values
on $fees
(uncomment last line).
The output is the following:
Array
(
[0] => stdClass Object
(
[id] => 1
[proposed_fee] => 25000
[student_id] => 1
[feeType_id] => 2
)
[1] => stdClass Object
(
[id] => 2
[proposed_fee] => 27000
[student_id] => 1
[feeType_id] => 1
)
[2] => stdClass Object
(
[id] => 3
[proposed_fee] => 9000
[student_id] => 1
[feeType_id] => 11
)
[3] => stdClass Object
(
[id] => 4
[proposed_fee] => 1000
[student_id] => 1
[feeType_id] => 16
)
)