Reputation: 1077
I have two loops and I need to combine them to a list
if ( have_rows('product_a')) :
while ( have_rows('product_a') ) : the_row();
echo get_field('product_name');
endwhile;
endif;
if ( have_rows('product_b')) :
while ( have_rows('product_b') ) : the_row();
echo get_field('product_name');
endwhile;
endif;
so the output would be like this, so combining them in a list
* product_a name
* product_B name
only if I could do this code below
if ( have_rows('product_a && product_b')) :
while ( have_rows('product_a && product_b') ) : the_row();
echo get_field('product_name');
endwhile;
endif;
I have tried this code and its working but is this a good practice
if ( have_rows('product_a') || have_rows('product_b') ) :
while ( have_rows('product_a') || have_rows('product_b') ) : the_row();
and also another problem, get_row_index() only counts 1 instead of 2
Upvotes: 1
Views: 55
Reputation: 2534
You could save the values in arrays and do the output later:
$array_counter = 0;
$product_a = [];
$product_b = [];
if ( have_rows('product_a')) :
while ( have_rows('product_a') ) : the_row();
$product_a[$counter] = get_field('product_name');
$counter++;
endwhile;
endif;
if ( have_rows('product_b')) :
while ( have_rows('product_b') ) : the_row();
$product_b[$counter] = get_field('product_name');
$counter++;
endwhile;
endif;
So you have your arrays. You now want to combine them in an alternating order:
$combined = [];
$length = count($product_a);
for ($i=0; $i < $length ; $i++) {
$combined[] = $product_a[$i];
$combined[] = $product_b[$i];
}
In each iteration, one item from each of the arrays will be appended to the combined-array. So you have you products in the right order.
Now you can just run through your array and output every value one by one:
$full_length = count($combined);
$counter = 0;
while ($counter < $full_length ) {
echo '<li>'.$combined[$counter].'</li>';
}
Upvotes: 1