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)
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;
PHP 7 solution:
$result = array_sum(array_column($array_of_objects, 'rating')) / 5;
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 .