I have a web form that allows users to enter details for creating a shipping consignment for 1 more more items. They enter the address from/to fields and then there's a section where they can enter 1 or more rows for items to be included on the shipment.
When the user submits the form I get the following Array:
(
[action] => createConsignment
[type] => Outgoing Domestic Shipment
[parcelID] => Array
(
[0] => DS851234
[1] => SM897452
)
[productID] => Array
(
[0] => XT71121
[1] => PL12134
)
[ref] => 3902381720
)
which I then process to create records in a backend database like this:
foreach($_POST["productID"] as $productID) {
$request->setField('productID', $productID);
}
This is working well but I now need to also include the parcelID when creating the new row in the backend database. So as well as getting the productID I need to get the parcelID with the same array position, so in the above example I would create a new row in the database with these pairs of values:
DS851234 and XT71121
SM897452 and PL12134
I can't work out how to reference both of these in the same foreach
loop to get the values for the same array position at the same time.
CodePudding user response:
You can use the array key as follows:
foreach($_POST['productID'] as $key => $productID) {
// ... do something with $productID
// ... use the matching parcelID as $_POST['parcelID'][$key]
This relies on the inputs in the form appearing in the same order, obviously, so the keys of each array match up.