
[英]Exclude woocommerce tax from multiple product variants based on user role
[英]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语句是微不足道的(只是连接几个字符串内爆)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.