小编典典

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

algorithm

我正在编写一个电子商务网站,并且需要一种计算产品差异的好方法。该站点具有产品,产品可以具有许多选项组,选项组可以具有许多选项。

因此,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;
}

阅读 260

收藏
2020-07-28

共1个答案

小编典典

这应该可以解决问题:

<?

$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

2020-07-28