0

I want all rating values sum then divided with 5

  array (size=2)
      0 => 
        object(stdClass)[571]
          public 'rating' => string '3' (length=1)
      1 => 
        object(stdClass)[300]
          public 'rating' => string '5' (length=1)
2
  • Start writing code. Commented Apr 28, 2017 at 8:59
  • use a foreach() & extract all the element's value & calculate the Sum. Then divide by 5. Ref - php.net/manual/en/control-structures.foreach.php Commented Apr 28, 2017 at 9:01

4 Answers 4

0

You can either use a 'foreach' block, iterate over each element in your array and sum up its 'rating' value

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

Or you can use the array_sum() method

    $sum =array_sum((int)$array->rating);
    $result = $sum/5;
Sign up to request clarification or add additional context in comments.

Comments

0

PHP 7 solution:

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

Comments

0

you can use this code for sum array value using php . First assign variable shich store all sum value so this must set 0 and use loop for make all value sum. this is your code which help you and if your array $your_array then

$sum = 0; // this is store all sum value so first assign 0
foreach ($your_array as $rating)  {          
{
   $sum += $rating->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 $total_sum = $sum / 5; // this is your desire result 

and if your array is associative then use this code

$sum = 0; // this is store all sum value so first assign 0
foreach ($your_array as $rating)  {          
{
   $sum += $rating['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 $total_sum = $sum / 5; // this is your desire result 

check this code and hope it will help you .

Comments

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

for average, I think you should divide sum by no. of result like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.