如何求和数组值php

时间:2017-04-28 08:57:33

标签: php

我希望所有评级值总和然后除以5

  array (size=2)
      0 => 
        object(stdClass)[571]
          public 'rating' => string '3' (length=1)
      1 => 
        object(stdClass)[300]
          public 'rating' => string '5' (length=1)

3 个答案:

答案 0 :(得分:0)

您可以使用' foreach'阻止,遍历数组中的每个元素并总结其评级'值

    foreach($array->items as $item) {
    $sum+=(int)$item->rating;            
    } 
    $result = $sum/5;

或者您可以使用array_sum()方法

    $sum =array_sum((int)$array->rating);
    $result = $sum/5;

答案 1 :(得分:0)

PHP 7解决方案:

$result = array_sum(array_column($array_of_objects, 'rating')) / 5;

答案 2 :(得分:-1)

$sum = 0;
foreach($array as $val){
    $sum += (int) $val->rating;
}
// divide by 5 
$average = $sum/5;

平均而言,我认为你应该将总和除以否。结果如

$average = $sum/count($array);