I have data like in the image above, and what I want is calculate it
so, it can be showing value = 4
this is my code
foreach($total_score as $total){ $score = $total->score; debug($score); $score += $score; } echo $score;
I have data like in the image above, and what I want is calculate it
so, it can be showing value = 4
this is my code
foreach($total_score as $total){ $score = $total->score; debug($score); $score += $score; } echo $score;
More context would be helpful to really understand your overall situation, however we can start with:
$score = 0;
foreach($total_score as $total){
$score += $total->score;
debug($score);
}
echo $score;
You were summing at the end but resetting $score every time at the beginning.
$score += $score
adds the current score to itself. Same as saying $score = $score * 2
. And it happens every time you add a new total to it. Add a total, double what you have so far. Add another total to that, and double the new result. And so on. Which is almost certainly not how scores should work.
A foreach will get it, but why not use the aggregate SUM.
thankyou so much guys, it’s working…
do you have any references to do this?
To use Cake’s Collection::sumOf
there is this and if you want to use the Query::sum
there is this
amazing bro, thank you