Php 只有最后一项保留在通过循环推送的数组上
我正在Woocommerce的Wordpress上做一个项目。我尝试获取特定类别的所有产品,将它们保存在一个数组中,然后使用它们执行我的操作。但是,即使循环工作并打印所有项目,当我将数据推送到数组上时,它也只保留最后一个项目Php 只有最后一项保留在通过循环推送的数组上,php,arrays,wordpress,woocommerce,Php,Arrays,Wordpress,Woocommerce,我正在Woocommerce的Wordpress上做一个项目。我尝试获取特定类别的所有产品,将它们保存在一个数组中,然后使用它们执行我的操作。但是,即使循环工作并打印所有项目,当我将数据推送到数组上时,它也只保留最后一个项目 $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'additional-number' ); $loop = new WP_Query(
$args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'additional-number' );
$loop = new WP_Query( $args );
echo '<select class="form-control">';
echo '<option>Select a country</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$countries = array();
$countries[] = $product->id;
echo '<option value="' . $product->id . '">' . $product->post->post_title . '</option>';
endwhile;
echo '</select>';
wp_reset_query();
print_r($countries);
知道我做错了什么吗?请添加$countries=array();前while循环
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'additional-number' );
$loop = new WP_Query( $args );
$countries = array();
echo '<select class="form-control">';
echo '<option>Select a country</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$countries[] = $product->id;
echo '<option value="' . $product->id . '">' . $product->post->post_title . '</option>';
endwhile;
echo '</select>';
wp_reset_query();
print_r($countries);
?>
请添加$countries=array();前while循环
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'additional-number' );
$loop = new WP_Query( $args );
$countries = array();
echo '<select class="form-control">';
echo '<option>Select a country</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$countries[] = $product->id;
echo '<option value="' . $product->id . '">' . $product->post->post_title . '</option>';
endwhile;
echo '</select>';
wp_reset_query();
print_r($countries);
?>
您正在循环内初始化数组变量,以便在每次迭代中创建一个新的空数组
$countries = array();
属于
循环之前,而循环。在循环内部初始化数组变量,以便在每次迭代中创建一个新的空数组
$countries = array();
属于while
循环之前