I'im trying to display all combinations of attributes of several arrays with associated price input, for user to fill in. After that, input values are to be saved into database.
For this example, I'm using 3 arrays:
[1] => Array
(
[8] => Small
[1] => Round
)
[2] => Array
(
[6] => 2 Layers
[4] => 1 Layer
)
[3] => Array
(
[10] => no fruit
[9] => w/ fruit
)
With the following combination function
function combination($array, $str = '', $valueKeys = '') {
$current = array_shift($array);
if(count($array) > 0) {
foreach($current as $k => $element) {
$valueKeys .= $k.'+';
combination($array, $str.' + '.$element, $valueKeys);
}
}
else{
foreach($current as $k => $element) {
$valueKeys .= $k;
echo '<label>'.substr($str, 3).' + '.$element . '</label> = <input name="attrib_price_'.$valueKeys.'" value="" /><br />' . PHP_EOL;
$valueKeys = '';
}
}
}
HTML Output
<label>Small + 2 Layers + no fruit</label> = <input name="attrib_price_8+6+10" value="" /><br />
<label>Small + 2 Layers + w/ fruit</label> = <input name="attrib_price_9" value="" /><br />
<label>Small + 1 Layer + no fruit</label> = <input name="attrib_price_8+6+4+10" value="" /><br />
<label>Small + 1 Layer + w/ fruit</label> = <input name="attrib_price_9" value="" /><br />
<label>Round + 2 Layers + no fruit</label> = <input name="attrib_price_8+1+6+10" value="" /><br />
<label>Round + 2 Layers + w/ fruit</label> = <input name="attrib_price_9" value="" /><br />
<label>Round + 1 Layer + no fruit</label> = <input name="attrib_price_8+1+6+4+10" value="" /><br />
<label>Round + 1 Layer + w/ fruit</label> = <input name="attrib_price_9" value="" /><br />
The combinations are all showed, but i have a problem with the price input names, they should include the attribute keys but only the first one is correct (8+6+10). How can I tweak the code to accomplish this? Suggestions welcomed. Thanks!