如何在PHP中从具有关联输入字段的数组中生成所有属性组合


How to generate all attribute combinations from arrays with associated input field in PHP

我正在尝试显示几个数组的所有属性组合以及相关的价格输入,供用户填写。之后,输入值将保存到数据库中。

对于这个例子,我使用了3个数组:

[1] => Array
    (
        [8] => Small
        [1] => Round
    )
[2] => Array
    (
        [6] => 2 Layers
        [4] => 1 Layer
    )
[3] => Array
    (
        [10] => no fruit
        [9] => w/ fruit
    )

具有以下组合功能

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输出

<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 />

组合都显示了,但我对价格输入名称有问题,它们应该包括属性键,但只有第一个是正确的(8+6+10)。我如何调整代码来实现这一点?欢迎提出建议。谢谢

在else部分中清除$valueKeys,这就是为什么在下一次迭代中只打印最后一个元素。在If部分中,您将上一次迭代的值附加到$valueKey:

function combination($array, $str = '', $valueKeys = '') {
   $current = array_shift($array);
   if(count($array) > 0) {
       foreach($current as $k => $element) {
           combination($array, $str.' + '.$element, $valueKeys.$k.'+');
       }
   }
   else{
       foreach($current as $k => $element) {
           echo '<label>'.substr($str, 3).' + '.$element . '</label> = <input name="attrib_price_'.$valueKeys.$k.'" value="" /><br />' . PHP_EOL;
       }
   } 
}