如何将两个循环组合成一个查询wordpress



我有两个循环,我需要将它们组合成一个列表

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;

所以输出是这样的,所以将它们组合在一个列表中

* product_a name
* product_B name

只有当我能在下面做这个代码

if ( have_rows('product_a && product_b')) :
while ( have_rows('product_a && product_b') ) : the_row();
echo get_field('product_name');
endwhile;
endif;

我已经尝试过这个代码,它可以工作,但这是一个很好的做法吗

if ( have_rows('product_a') || have_rows('product_b') ) :
while ( have_rows('product_a') || have_rows('product_b') ) : the_row();

还有另一个问题,get_row_index((只计数1而不是2

您可以将值保存在数组中,然后进行输出:

$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;

所以你有你的数组。您现在想将它们按交替顺序组合:

$combined = [];
$length = count($product_a);
for ($i=0; $i < $length ; $i++) {
$combined[] = $product_a[$i];
$combined[] = $product_b[$i];
}

在每次迭代中,每个数组中的一个项将附加到组合数组中。所以你有你的产品在正确的顺序。

现在,您只需运行您的数组并逐个输出每个值:

$full_length = count($combined);
$counter = 0;
while ($counter < $full_length ) {
echo '<li>'.$combined[$counter].'</li>';
}

相关内容

最新更新