How to process groups of duplicate fields and organize by common field key - PHP / Array
Looking to mimic what's going on on this website where you can add multiple field groups: When you click "add another card", it duplicates the field -- I've got this covered with jquery and clone()
. However, if you input two gift cards with the same amount, on the next step they've combined the quantities for those gift cards into one group. So here's a scenario that I'm facing and the output that I would like to see:
User Input:
Field Group 1 -- Amount: $100 Quantity: 1
Field Group 2 -- Amount: $75 Quantity: 2
Field Group 3 -- Amount: $100 Quantity: 1
Desired Output on Next Page:
$100 Gift Card Group: 2
$开发者_JAVA技巧75 Gift Card Group: 2
I've been searching for different ways to do this and can't find anything, please help!!
For the inputs, I would use names like denomination[], quantity[], since we are processing arrays. On the next page, do a print_r() on $_POST, and then you can do a foreach() loop to combine quantities of the same denomination.
Now, suppose $foo is our (cleaned up) $_POST. Please perform a pre-processing loop to clean up the inputs; e.g. discarding invalid denominations/quantities as required.
Once this is done, we end up with $foo like:
<?php
// cleaned up $_POST
$foo = array(
'denomination' => array(100, 75, 100),
'quantity' => array(1, 2, 1),
);
$bar = array();
foreach ($foo['denomination'] as $d => $denomination) {
if (array_key_exists($denomination, $bar)) { // denomination exists
$bar[$denomination] += $foo['quantity'][$d];
} else { // new denomination
$bar[$denomination] = $foo['quantity'][$d];
}
}
print_r($bar); die; // debug
?>
The output is:
Array(
[100] => 2,
[75] => 2
)
精彩评论