我正在编写一个电子商务网站,需要一种计算产品变化的好方法。站点有产品,产品可以有很多选项组,选项组可以有很多选项。
所以一件 T 恤产品有 3 个选项组和选项:
尺寸: 小的, 中等的, 大,
颜色: 红色的, 蓝色的, 黄色的, 黑色,
Material : 棉布, 尼龙,
创建:小红棉、小红尼龙、小蓝棉、小蓝尼龙……等等
我知道下面的脚本可以工作,但也可以对其进行优化。任何人都可以提供一个更好的工作示例吗?也应该可以使用递归......但我遇到了心理障碍。
if(count($option_groups) > 1)
{
// start the variants up
foreach($option_groups[0]->get_options() as $option)
{
$variants[] = array($option);
}
// go through every other option group to make combos
for($x = 1; $x < count($option_groups); $x++)
{
$combos = array();
foreach($variants as $variant)
{
$new = array();
foreach($option_groups[$x]->get_options() as $option)
{
$tmp = $variant;
$tmp[] = $option;
$new[] = $tmp;
}
$combos[] = $new;
}
$variants = array();
foreach($combos as $combo)
{
foreach($combo as $tmp)
{
$variants[] = $tmp;
}
}
}
}
这对时间不是特别敏感,但我想要更易于维护的代码块,这太恶心了。
还有这个问题(我感觉不是原来的问题,很多推车都这样)有名字吗?我没有为这个问题在谷歌上搜索任何内容。
编辑 这就是我最终得到的结果,它基于 profitphp 的解决方案,但维护了我的对象,而不是为我提供连接为字符串的每个变体的选项。感谢 Profitphp!
private function _possible_combos($groups, $prefix = array())
{
$result = array();
$group = array_shift($groups);
foreach($group->get_options() as $selected)
{
if($groups)
{
$tmp = $prefix;
$tmp[] = $selected;
$result = array_merge($result, $this->_possible_combos($groups, $tmp));
}
else
{
$tmp = $prefix;
$tmp[] = $selected;
$result[] = $tmp;
}
}
return $result;
}
最佳答案
这应该可以解决问题:
<?
$data[]=array('shirt');
$data[]=array('red','yellow','black');
$data[]=array('small','medium','large');
$combos=possible_combos($data);
//calculate all the possible comobos creatable from a given choices array
function possible_combos($groups, $prefix='') {
$result = array();
$group = array_shift($groups);
foreach($group as $selected) {
if($groups) {
$result = array_merge($result, possible_combos($groups, $prefix . $selected. ' '));
} else {
$result[] = $prefix . $selected;
}
}
return $result;
}
echo count($combos) . "\n";
print_r($combos);
关于php - 根据选项组和选项计算产品变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324111/