I have a loop below that is showing a quantity box and includes a hidden field containing the product name.
I want these to be tied together so if out of 100 inputs the user changes the quantity of input 90, then and want the hidden field input 90 to be tied to it.
This then gives me the quantity and the product name for items that have more than zero.
<?php if(get_field('sizes')) {
while(the_repeater_field('sizes')) { ?>
<input type="text" name="quantity[]" value="0"> <?php the_title(); ?>
<input type="hidden" name="product[]" value="<?php the_title(); ?>">
<?php } } ?>
I want to tie these two together so it would echo out the following:
- 1 x Product One
- 10 x Product Three
- 20 x Product Eight
How can I output the quantity AND product name only if the quantity is more than zero?
This is the actual code used:
<?php if(get_field('sizes')) { ?>
<?php while(the_repeater_field('sizes')) { ?>
<tr>
<td width="150"><p><?php echo the_sub_field('size'); ?></p></td>
<td width="30" align="right">
<p>
<input type="text" class="quantity" name="quantity[]" style="width:15px;text-align:center!IMPORTANT;margin-left:10px;" value="0">
<input type="hidden" class="productinput" name="product[]" value="<?php echo the_title(); ?> - <?php echo the_sub_field('size'); ?>"></td>
</p>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td width="150"><p>Quantity</p></td>
<td width="30" align="right">
<p>
<input type="text" class="quantity" name="quantity[]" style="width:15px;text-align:center!IMPORTANT;margin-left:10px;" value="0"><?php echo the_sub_field('size'); ?>
<input type="hidden" class="productinput" name="product[]" value="<?php echo the_title(); ?>">
</p>
</td>
</tr>
<?php } ?>
This is then creating the code ready to be output in an email:
$quantities = array_combine($_POST['product'], $_POST['quantity']);
foreach ($quantities as $product => $quantity) {
if ($quantity > 0) {
$productresults = "$quantity x $product";
}
}
This is the page I’m working on. If you click on “Get Quotation”, the second step is the code above.
@Sn0opy
foreach($_POST['quantity'] as $check) {
if($check > 0) {
$quantityresults .= $check."\n";
}
}
echo $quantityresults;
You obviously need to iterate over both arrays in tandem so that you can see if a product’s quantity is nonzero in order to decide if it should be displayed.
In general
foreachis an awkward tool for this job, and the way to go is with aforloop and indexing into both arrays using the same counter. However, in this specific case you can easily transform your two arrays into one where the keys are product names and the quantities are the values usingarray_combine:You can then easily iterate with
foreach: