calculate product variants based on option groups and options

邮差的信 提交于 2019-11-30 10:03:11

This should do the trick:

<?

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

Tested: http://www.ideone.com/NZE5S

If this is an e-commerce site my guess is your option groups are already in an SQL database so why not just let SQL do the combinations for you.

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

But what if you had all your options in one table with a foreign key to the group it's in...

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

Once you have an array containing the group IDs generating the SQL statement above is trivial (just concatenating a few string implodes).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!