根据选项组和选项计算产品变体


calculate product variants based on option groups and options

我正在写一个电子商务网站,需要一个很好的方法来计算产品的变化。网站有产品,产品可以有很多选项组,选项组可以有很多选项。

一个t恤产品有3个选项组和选项:

:小,介质,大,

:红色,蓝色,黄色的,黑色,

:棉花,尼龙,

产生:小红棉,小红尼龙,小蓝棉,小蓝尼龙,…等等

我知道下面的脚本工作,但它也可以优化。有人能提供一个更好的例子吗?使用递归也应该是可能的……但是我脑子里出问题了

    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);

测试:http://www.ideone.com/NZE5S

如果这是一个电子商务网站,我猜你的选项组已经在SQL数据库中了,所以为什么不让SQL为你做组合呢?

SELECT Size.Name, Color.Name, Material.Name FROM Size, Color, Material

但是如果你把所有的选项都放在一个表中,并且有一个外键指向它所在的组…

SELECT r1.Name, r2.Name, r3.Name 
FROM Options r1, Options r2, Options r3
WHERE r1.GroupID = 1 -- id for Size
    AND r2.GroupID = 2 -- id for Color
    AND r3.GroupID = 3 -- id for Material

一旦您有了一个包含组id的数组,生成上面的SQL语句就很简单了(只是连接几个字符串内爆)。