javascript - How to process groups of duplicate fields and organize by common field key - PHP / Array -
looking mimic what's going on on website can add multiple field groups: when click "add card", duplicates field -- i've got covered jquery , clone()
. however, if input 2 gift cards same amount, on next step they've combined quantities gift cards 1 group. here's scenario i'm facing , output 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 $75 gift card group: 2
i've been searching different ways , can't find anything, please help!!
for inputs, use names denomination[], quantity[], since processing arrays. on next page, print_r() on $_post, , can foreach() loop combine quantities of same denomination.
now, suppose $foo our (cleaned up) $_post. please perform pre-processing loop clean inputs; e.g. discarding invalid denominations/quantities required.
once done, end $foo like:
<?php // cleaned $_post $foo = array( 'denomination' => array(100, 75, 100), 'quantity' => array(1, 2, 1), ); $bar = array(); foreach ($foo['denomination'] $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 )
Comments
Post a Comment