Generating Product SKU Combinations Using Cartesian Product in PHP
This article explains how to generate all possible product SKU combinations for an e‑commerce system by computing the Cartesian product of specification arrays, and provides two PHP implementations—one that returns SKU strings and another that returns nested arrays—along with sample output.
The author is building an e‑commerce system and needs to batch‑generate product SKUs after adding various specifications such as color, storage, carrier, and region.
SKU generation is achieved by calculating the Cartesian product of the specification arrays, and two PHP approaches are demonstrated.
First method – generate SKU strings:
<?php
function Cartesian($data){
$len = count($data);
for($i = 0; $i < $len-1; $i++){
if($i === 0){
// first array
$result = $data[0];
}
$temp = [];
// combine current result with next array
foreach($result as $res){
foreach($data[$i+1] as $sec){
$temp[] = $res . '-' . $sec;
}
$result = $temp;
}
}
return $result;
}
// data to compute
$data = array(
array('白色','银色','玫瑰金'),
array('64G','128G'),
array('移动','电信','联通'),
array('国行','港版')
);
$result = Cartesian($data);
print_r($result);
?>The function returns a flat array of SKU strings such as "白色-64G-移动-国行".
Second method – generate nested array format:
<?php
function Cartesian($data){
$len = count($data);
// take first set
$result = $data[0];
for($i = 0; $i < $len-1; $i++){
$arr1 = $result;
$result = [];
foreach($arr1 as $res){
foreach($data[$i+1] as $sec){
if(!is_array($res)) $res = array($res);
if(!is_array($sec)) $sec = array($sec);
$result[] = array_merge_recursive($res,$sec);
}
}
}
return $result;
}
$data = array(
array('白色','银色','玫瑰金'),
array('64G','128G'),
array('移动','电信','联通'),
array('国行','港版')
);
$result = Cartesian($data);
print_r($result);
?>This version returns a multi‑dimensional array where each SKU component remains in its own sub‑array, as shown by the printed result.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.