我试图显示几个数组的所有属性组合以及相关的价格输入,供用户填写。之后,输入值将保存到数据库中。
对于这个例子,我使用了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)。我如何调整代码来实现这一目标? 建议欢迎。谢谢!
答案 0 :(得分:0)
在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;
}
}
}