Iterate through loop and add variables together
-
07-07-2021 - |
Domanda
I have the following loop which shows the fields money and percent. I want to add all the money together as it iterates through, how can I do this and echo out a total outside the loop?
while(the_repeater_field('income')) {
the_sub_field('money');
the_sub_field('percent');
}
Soluzione
<?php
$Sum_Money = 0;
$Sum_Percent = 0;
while (the_repeater_field('income')) {
$Money = the_sub_field('money');
$Percent = the_sub_field('percent');
$Sum_Money += $Money;
$Sum_Percent += $Percent;
}
echo $Sum_Money;
Altri suggerimenti
Edited to reflect the new format of the question. Here is the answer:
<?php
$total = 0;
$totalPercent = 0;
while(the_repeater_field('income')) {
$total += the_sub_field('money');
$totalPercent += the_sub_field('percent');
}
echo "Total: $total, Percent: $totalPercent";
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow