dongpangzan6425 2017-04-28 10:52 采纳率: 100%
浏览 242
已采纳

PHP - >如何使用foreach对数组值求和

I am new developer. I have a problem. I want all rating value sum then divided with 5. foreach show 325. I want result 3+2+5=10 then 10/5=2

 foreach ($ratings as $ratingss)  {                          
     echo $ratingss->rating ;
     }

var dump

object(stdClass)[571]
  public 'id' => string '12' (length=2)
  public 'hotel_id' => string '37' (length=2)
  public 'rating' => string '3' (length=1)

object(stdClass)[300]
  public 'id' => string '13' (length=2)
  public 'hotel_id' => string '37' (length=2)
  public 'rating' => string '5' (length=1)
  • 写回答

1条回答 默认 最新

  • dongyimo1293 2017-04-28 10:55
    关注

    You can use this code. It will sum all values and put in the $sum variable.

    if your array object(stdClass) -> then

    $sum = 0; // this is store all sum value so first assign 0
    foreach ($ratings as $ratingss)          
    {
       $sum += $ratingss->rating; // sum value with previous value and store it and no need to convert string type to int cause php do it 
    }
    echo $sum; // this is final value
    echo $final_result = $sum / 5; // this is your desire result 
    

    if your array -> associative array then

    $sum = 0; // this is store all sum value so first assign 0
    foreach ($ratings as $ratingss)           
    {
       $sum += $ratingss['rating']; // sum value with previous value and store it and no need to convert string type to int cause php do it 
    }
    echo $sum; // this is final value
    echo $final_result = $sum / 5; // this is your desire result 
    

    hope this will help you

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?