Home › Forums › General Issues › Get max value from two arrays inside two ACF nested repeaters
I want to build a function that will echo/display the highest (max) value from two different arrays (repeater fields). The difficulty of the task lies into a specific construction of my repeaters / fields which looks as follows:
+Main repeater (called ‘sales’)
++sub_field(‘all_regions_percentage_off’)
++Nested repeater (called ‘different_regions’)
+++ sub_field(‘percentage_off’)
All of the subfields are text one, in which a user inputs numbers. So at the end I would like to display a single value which would the highest among those two fields/arrays. I have the following code:
<?php
$groupA = array();
$groupB = array();
if( have_rows('sales') ):
while( have_rows('sales') ) : the_row();
$groupA[] = get_sub_field('all_regions_percentage_off');
if( have_rows('different_regions') ):
while( have_rows('different_regions') ) : the_row();
$groupB = array_push($groupA, get_sub_field('percentage_off'));
endwhile;
endif;
echo '<pre>'.print_r($groupB).'</pre>';
endwhile;
else : echo 'Nothing here, sorry';
endif;
?>
But it doesn’t work and I have no idea why. Plus if the repeater has more than 1 row, the loop displays multiple outputs. Obviously it might be a thing of adding an counter like:
$i = 0; // before first while of the main repeater
if(!$i++) { code here } // as a wrapping element for the first subfield and the entire nested repeater
But again the main issue is in a different place = showing a single value that will be a MAX from both fields (all_regions_percentage_off and percentage_off).
Thanks for any tips and suggestions.
I think one of your problems is that you are using strings (text fields) to store numbers, but I’m not sure because you didn’t display the code that is outputting the max value.
I would likely to something like this
$max = 0;
if (have_rows('sales') {
while (have_rows('sales')) {
the_row()
$value = intval(get_sub_field('all_regions_percentage_off'));
if ($value > $max) {
$max = $value;
}
if (have_rows('different_regions')) {
while (have_rows('different_regions')) {
the_row();
$value = intval(get_sub_field('percentage_off'));
if ($value > $max) {
$max = $value;
}
}
}
}
}
echo $value;
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.