tags:

views:

35

answers:

3

I've been developing a dynamically generated form that passes multiple items similar to the sample below to a PHP script.

<div class="menu-item">
<input type="text" value="3" readonly="readonly" class="quantity" name="quantity">
<input type="text" value="Menu Item 3" readonly="readonly" class="item" name="item">
<input type="text" value="80.00" readonly="readonly" class="price" name="price">
</div>
...etc

My issue is because I'm not giving the name attribute for quantity, item and price a unique identifier I'm getting these kinds of parameters passed through to the server side:

quantity=3&item=Menu+Item+3&price=80.00&quantity=2&item=Menu+Item+2&price=50.00&quantity=1&item=Menu+Item+1&price=30.00&total=370.00&name=Alex&table=10&terms=on

I can easily alter it so the names would be quantity1, item1, price1, quantity2, item2, price2, etc but either way I'm not sure how best to loop round those sets of parameters using PHP so I can make sure that I process each quantity, item and price that correspond to an item.

Thanks, Alex

+6  A: 

If you name the fields like quantity[], item[], and price[], PHP will assemble them into an array named after each thing. Just make sure all the quantities, items, and prices are in the same order on the page (and none of them skip a field), and $_POST['quantity'][0] will be the first quantity, $_POST['price'][0] the first price, etc.

cHao
+1... You are very fast :-)
a1ex07
I'm bored. Doing nothing atm but looking through SO for questions to answer and rep to gain. :)
cHao
thanks CHao, nice solution
Alex
A: 

What I usualy do is the following:

Generate your form with the following names: quantity-x, item-x, price-x;

This is how you process it:

$values = array();
foreach($_POST AS $key => $value ){
$keyPart = explode('-',$key);
$values[$keyPart[1]][$keyPart[0]] = $value
}

This will generate an array where each element contains an array with your grouped values. So element 0 would be [quantity-1,price-1,item-1] and 1 would be [quantity-2,price-2,item-2]

The value of this way is that you do not have to keep track of the order of your elements. As the unique identifier could be directly linked to a database primary key. Downside is, you will have to itterate twice.

EDIT: This will also work on $_GET

jpluijmers
A: 

Assuming that you have only those variables coming in through GET, this would be one way:

//number of fields/item
$fields = 3;
$itemCount = count($_GET) / $fields;

for ($i = 1; i <= $fields; i++) {
     $quantity = $_GET['quantity'.i];
     $item = $_GET['item'.i];
     $price = $_GET['price'.i];
     processFields($quantity, $item, $price);
}
Ender