calculate product variants based on option groups and options

前端 未结 2 1856
一向
一向 2020-12-29 18:00

I am writing an ecommerce site, and need a good way to calculate product variations. The Site has products, products can have many option groups, option groups can have many

相关标签:
2条回答
  • 2020-12-29 18:08

    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).

    0 讨论(0)
  • 2020-12-29 18:13

    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

    0 讨论(0)
提交回复
热议问题