我找到了Sum values in foreach loop php
但我需要适应我的情况。我有三个等级的表和user_id
。我需要在管理表中获得每个用户的所有评级的平均值。例如,如果用户制作了两部作品并且有5,5,5和5,5,4我想要显示4.835,但我得到的是:
user_id - 平均值
200 - 4.67 | 4.835 |
我需要:
200 - 4.835
控制器:
$feedbacks = DB::table('feedback')->groupBy('user_id')->paginate(100);
$feedbacks_get = DB::table('feedback')->get();
刀片:
@foreach( $feedbacks as $wrk)
<tr>
<td>
{{$wrk->user_id}}
</td>
<td>
<?php $sum = 0;$i = 0;?>
@foreach($feedbacks_get as $e)
@if ( $e->user_id == $wrk->user_id)
<?php
$i++;
$sum+= (($e->rating1 + $e->rating2 + $e->rating3 ))/3;
$result= round($sum,2)/$i .' | ';
if($result<=4){
echo '<span class="red;">'.$result.'</span>' ;
}
elseif($result>4){
echo $result;
}
?>
@endif
@endforeach
</td>
</tr>
@endforeach
答案 0 :(得分:1)
@foreach( $feedbacks as $wrk)
<tr>
<td>
{{$wrk->user_id}}
</td>
<td>
<?php $sum = 0;$i = 0;?>
@foreach($feedbacks_get as $e)
@if ( $e->user_id == $wrk->user_id)
<?php
$i++;
$sum+= (($e->rating1 + $e->rating2 + $e->rating3 ))/3;
?>
@endif
@endforeach
$result= round($sum,2)/$i ;
if($result<=4){
echo '<span class="red;">'.$result.'|</span>' ;
}
elseif($result>4){
echo $result.' | ';
}
</td>
</tr>
@endforeach
答案 1 :(得分:0)
Laravel中数据库查询的结果始终是Laravel Collection,因此您可以使用这些函数自动执行此操作:
nfs-pv.yaml