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?