I'm doing a query in laravel to bring me a sum according to the field I'm calling, my problem is that I make a conversion to get the average and I need to round to two decimals, and use the function round
for me to round to two decimals but I'm not rounding it, maybe I'm implementing it badly or I do not know how it works, I'll leave the laravel code to collaborate with me
$collection = Precebo::join('granjas','granjas.id','=','formulario_precebo.granja_id')
->select('granja_id','granjas.nombre_granja','año_destete',DB::raw('sum(numero_inicial) as total'))
->whereIn('año_destete',$request->desde)
->groupBy('granjas.nombre_granja','año_destete')->get();
$arrayT = [];
foreach ($collection as $value) {
$arrayT[]=[$value->granja_id,$value->nombre_granja,$value->total,$value->año_destete];
}
$granjas = $request->array;
$annios = $request->desde;
$an = $request->annos;
$categories = array();
foreach ($annios as $years) {
foreach ($an as $y) {
if ($years == $y) {
$categories[] = $y;
}
}
}
$array = array();
$promedios = array();
foreach ($granjas as $granja) {
$values = array();
foreach ($annios as $year) {
$anoencontrado = 0;
foreach ($arrayT as $data) {
if ($granja == $data[0]) {
$value = $data[3] ? $data[2] : 0;
if ($data[3] == $year) {
$values[] = $value;
$anoencontrado = 1;
}
}
}
if ($anoencontrado === 0) {
$values[] = 0;
}
}
foreach ($arrayT as $data) {
if ($granja == $data[0]) {
$array[]=array(
'name' => $data[1],
'data' => $values
);
$suma = 0;
foreach ($values as $value) {
$suma += $value;
}
$promedios[]= array(
'name'=> $data[1],
'value'=>(count($values) !== 0)? $suma / count($values) : 0
);
break;
}
}
}
$suma = 0;
$suma_granjas = 0;
foreach ($array as $arra) {
$suma_granjas++;
}
foreach ($promedios as $promedio) {
$suma += $promedio['value'];
}
$promedioGeneral = ($suma_granjas !== 0) ? $suma / $suma_granjas : 0;
round($promedioGeneral);
return response()->json(['status'=>'success','data'=>$array,'categories'=>$categories,'general'=>$promedioGeneral,'granjas'=>$suma_granjas],200);