Backend Development 3 min read

Generating SKU Combinations with Cartesian Product in PHP

This article demonstrates how to generate all possible SKU combinations in PHP by using Cartesian product on color, size, and version arrays, includes a full code example and the resulting array output.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Generating SKU Combinations with Cartesian Product in PHP

It is possible to generate SKU combinations by applying a Cartesian product to three arrays representing colors, sizes, and versions. First, the arrays are merged into a two‑dimensional array, then the Cartesian product function creates every possible combination, resulting in a complete SKU list.

Example PHP code:

<code>// 颜色数组
$colors = array('红色', '蓝色', '绿色');
// 尺寸数组
$sizes = array('S', 'M', 'L');
// 版本数组
$versions = array('V1', 'V2', 'V3');

$combinations = array();
foreach ($colors as $color) {
    foreach ($sizes as $size) {
        foreach ($versions as $version) {
            $combinations[] = array('颜色' => $color, '尺寸' => $size, '版本' => $version);
        }
    }
}

function cartesianProduct($arr) {
    $result = array();
    foreach ($arr as $key => $values) {
        if (empty($values)) {
            continue;
        }
        if (empty($result)) {
            foreach ($values as $value) {
                $result[] = array($key => $value);
            }
        } else {
            $append = array();
            foreach ($result as &$product) {
                $product[$key] = array_shift($values);
                $copy = $product;
                foreach ($values as $item) {
                    $copy[$key] = $item;
                    $append[] = $copy;
                }
                $values = array_values($values);
            }
            $result = array_merge($result, $append);
        }
    }
    return $result;
}

$skus = cartesianProduct($combinations);
print_r($skus);
</code>

The printed result is an array where each element contains a specific combination of color, size, and version, for example:

<code>Array
(
    [0] => Array
        (
            [颜色] => 红色
            [尺寸] => S
            [版本] => V1
        )
    [1] => Array
        (
            [颜色] => 红色
            [尺寸] => S
            [版本] => V2
        )
    ...
)
</code>

Note: The original source also contains promotional information about a PHP live class, which is not part of the technical tutorial.

arrayCode Examplecartesian productSKU
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.