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

Fra*_*llo 5 php algorithm e-commerce

我正在撰写电子商务网站,需要一种很好的方法来计算产品差异.该网站有产品,产品可以有很多选项组,选项组可以有很多选项.

所以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;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这不是超级时间敏感的,但我希望有一个更易维护的代码块,这是非常严重的.

也有这个问题(我觉得这不是一个原始的问题,许多推车这样做)有一个名字?我没有在谷歌上解决这个问题.

编辑 这是我最终得到的,它基于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;
}
Run Code Online (Sandbox Code Playgroud)

pro*_*php 7

这应该做的伎俩:

<?

$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);
Run Code Online (Sandbox Code Playgroud)

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