php - Only last item is kept on an array push through a loop -


i working on project woocommerce in wordpress. try products of specific category, save them in array , things them. however, if loop works , prints items, when push data on array, keeps last one.

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

as can see, select build one:

<select class="form-control">     <option>select country</option>     <option value="7818">england</option>     <option value="7814">germany</option> </select> 

but output of print_r one:

array (     [0] =&gt; 7814 ) 

any idea doing wrong?

please add $countries = array(); before while loop

<?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 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); ?> 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -