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

时间:2017-04-28 10:52:28

标签: php

我是新开发者。我有个问题。 我希望所有评级值总和然后除以5。 foreach show 325.我想要结果3 + 2 + 5 = 10然后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 个答案:

答案 0 :(得分:3)

您可以使用此代码。它将对所有值求和并放入$sum变量。

如果你的数组object(stdClass) - >然后

$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 

如果您的数组 - > associative array然后

$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 

希望这会对你有所帮助