user3066521
user3066521

Reputation:

Converting $_POST text input into a multidimensional array

On my online shop, there's a form with a big number of text inputs, representing quantities of products. There are three fields for every product: quantity of product in S size, M size and L size.

So the name of input field must contain both the product id and the size. This is simplified code of the form:

foreach ($productid as $id ) {
    echo '<input type="text" name="s'.$id.'" />';
    echo '<input type="text" name="m'.$id.'" />';
    echo '<input type="text" name="l'.$id.'" />';
}

I want to process this input sent via $_POST and save all values of all input field into a single multidimensional array. The format of the desired array is as follows:

$input['32']['m']='20' means that the customer ordered 20x the product of id 32 in size M.

All my tries to do that failed because I don't understand how to loop through $_POST values to turn them into more than a one-dimension array.

Any idea how to process such input and get a two-dimension array?

Upvotes: 0

Views: 782

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Brackets [] will make an array, so try this and print_r($_POST) and see:

foreach ($productid as $id ) {
    echo '<input type="text" name="product['.$id.'][s]" />';
    echo '<input type="text" name="product['.$id.'][m]" />';
    echo '<input type="text" name="product['.$id.'][l]" />';
}

Upvotes: 1

Related Questions