I have a repeater called “project_task_group”, with another repeater inside this called “project_task”. There’s a numerical sub-field in the “project_task” repeater called “project_task_percentage”, containing a value between 0 to 100. I’d like to be able to sum all the values of this field for each “project_task” and divide them by the amount of “project_taks”‘s in order to display an average for each “project_task_group”. I’ve been able to work out how to count the amount of “project_task”‘s, but I haven’t a clue how to add all the values of the sub-fields, so I’d really appreciate some help. My simplified code is as follows:
<h1>Tasks</h1>
<?php if( have_rows('project_task_group') ): while ( have_rows('project_task_group') ) : the_row(); ?>
<div class="taskgroup">
<h1><?php the_sub_field('project_task_group_name'); ?></h1>
<p>Total Tasks in Group: <?php $tasks = get_sub_field('project_task'); echo $totaltasks = count($tasks); ?></p>
<p>Total Percentage <?php //show total sum of project_task_percentage value for each task divided by the total amount of tasks ?></p>
<?php if( have_rows('project_task') ): while ( have_rows('project_task') ) : the_row(); ?>
<div class="eachtask">
<h2><?php the_sub_field('project_task_title'); ?></h2>
<p><?php the_sub_field('project_task_percentage'); ?></p>
</div>
<?php endwhile; else : ?>
<p>No tasks have been added yet.</p>
<?php endif; ?>
</div>
<?php endwhile; else : ?>
<p>No task groups have been added yet.</p>
<?php endif; ?>
Many thanks.
Here is the code I came up with, just in case anyone else finds it useful:
<?php
$tasks = get_sub_field('project_task'); $totaltasks = count($tasks);
$totaltaskpercentage = 0;
while ( have_rows('project_task') ) : the_row();
$totaltaskpercentage += intval( get_sub_field('project_task_percentage'));
endwhile;
$grouptaskpercentage = $totaltaskpercentage / $totaltasks;
echo round($grouptaskpercentage);
?>