【发布时间】:2011-09-06 17:57:26
【问题描述】:
我正在编写一个电子商务网站,需要一种计算产品变化的好方法。该站点有产品,产品可以有很多选项组,选项组可以有很多选项。
所以一个 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;
}
【问题讨论】:
-
很有趣,这是我在面试时提出的问题,足够接近了。
-
不要以为你得到了任何好的(或至少比我写的更好)答案?
-
作为一个 Haskell 布道者,我不禁吹嘘这个功能是内置的:
sequence [["small", "medium", "large"], ["red", "blue", "yellow", "black"], ["cotton", "nylon"]] = [["small","red","cotton"],["small","red","nylon"],["small","blue","cotton"],["small","blue","nylon"], {- and a bunch more ... -}] -
如果 php 有这个功能那就太好了。
标签: php algorithm e-commerce