This is my array
array(
['studentId'=>"M100030","isbn"=>"0199535566",'price'=>"15.00"],
['studentId'=>"M100030","isbn"=>"0199535566",'price'=>"13.50"],
['studentId'=>"M100030","isbn"=>"0143105426",'price'=>"20.00"],
['studentId'=>"M100035","isbn"=>"1604501480",'price'=>"21.00"],
['studentId'=>"M100035","isbn"=>"1604501480",'price'=>"23.00"],
['studentId'=>"M100035","isbn"=>"0199535566",'price'=>"14.00"],
['studentId'=>"M103233","isbn"=>"0061964360",'price'=>"18.50"],
);
I want to group the studentId and isbn then sum up the price to JSON
{
"M100030":{
"0199535566":{
"amount":"28.50"
},
"0143105426":{
"amount":"20.00"
}
},
"M100035":{
"1604501480":{
"amount":"44.00"
},
"0199535566":{
"amount":"14.00"
}
},
"M103233":{
"0061964360":{
"amount":"18.50"
}
}
}
The method I tried so far to group the studentId and isbn, but not able to get the expected result. Anyone can correct my code?
foreach ($check['rentout'] as $key=> $values)
{
$keys = $values['studentId'];
if (!array_key_exists($keys,$trx)){
$trx[$keys] = array('isbn'=>$values['isbn'],'amount'=>$values['price']);
}else{
$trx[$keys]['amount'] = $trx[$keys]['amount']+$values['price'];
}
}