Reputation: 1948
I have a very simple form for products. Each product has a checkbox and quantity field that repeat creating an array of data like this:
<form action="process.php" method="post">
<input type="checkbox" name="product[]" value="product 1" />
<input type="text" name="quantity[]" />
<input type="checkbox" name="product[]" value="product 2" />
<input type="text" name="quantity[]" />
<input type="submit" />
</form>
Then I handle this form the following way in php:
//php script to retrieve data
$product = isset($_POST['product']) ? implode(', ', $_POST['product']) : 'Not selected';
$quantity = isset($_POST['quantity']) ? implode(', ', $_POST['quantity']) : 'Not mentioned';
$messageToSend = <<<END
Products: $product - $quantity
END;
And the output result is for example: Products: product 1, product 2 - 10, 2
But what I am trying to achieve is the following output: Products: product 1 - x 10, product 2 - x 2
Basically what I am trying to figure out is how to split and group data for each product in php script after I retrieved data.
Your help is very much appreciated.
Upvotes: 0
Views: 1750
Reputation: 395
You just have to iterate through both lists together:
foreach ($quantity as $key => $quant) {
echo $product[$key].' - x'.$quant;
}
This is the general idea, but as mentioned in the comments, doing this alone will is not the real solution.
Some things to keep in mind:
Upvotes: 3
Reputation: 1
Try this:
<?php
foreach($_POST['product'] as $key => $product){
$quantity = isset($_POST['quantity'][$key])? $_POST['quantity'][$key]:'Not selected';
$message[] = $product.' - x'.$quantity;
}
echo implode(',', $message);
?>
Upvotes: 0