CRCMS

高山仰止,景行行止,虽不能至,心向往之

大道至简


一个简单的电商规格算法

电商开发中我们最不可缺少的就是规格参数组合,一种简单算法如下:

function generateGroup()
{
    if (func_num_args() <= 1) {
        return func_get_arg(func_num_args());
    }

    $all = func_get_args();
    $first = array_shift($all);
    $second = array_shift($all);

    if (count($first) >= count($second)) {
        $outsideLoop = $first;
        $insideLoop = $second;
    } else {
        $outsideLoop = $second;
        $insideLoop = $first;
    }

    $component = [];
    if (empty($insideLoop) && empty($outsideLoop)) {
        $component = [];
    } elseif (empty($insideLoop)) {
        $component = $outsideLoop;
    } elseif (empty($outsideLoop)) {
        $component = $insideLoop;
    } else {
        foreach ($outsideLoop as $outsideItem) {
            foreach ($insideLoop as $insideItem) {
                $component[] = array_merge((array)$outsideItem, (array)$insideItem);
            }
        }
    }

    return empty($all) ? $component : generateGroup($component, ...$all);
}