This article brings you relevant knowledge about php and sku. It mainly introduces how php performs Cartesian product operations to obtain the sku array. There are code examples. Friends who are interested can take a look below. I hope everyone has to help.
You can use Cartesian product to achieve the combination of sku. Suppose there are three arrays, namely the color array, the size array and the version array. You can first combine them into a two-dimensional array, and then perform a Cartesian product operation to finally get the sku array.
The sample code is as follows:
`// 颜色数组 $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; } // 得到sku数组 $skus = cartesianProduct($combinations); // 输出sku数组 print_r($skus);`
The output result is as follows:
`Array ( [0] => Array ( [颜色] => 红色 [尺寸] => S [版本] => V1 ) [1] => Array ( [颜色] => 红色 [尺寸] => S [版本] => V2 ) [2] => Array ( [颜色] => 红色 [尺寸] => S [版本] => V3 ) [3] => Array ( [颜色] => 红色 [尺寸] => M [版本] => V1 ) [4] => Array ( [颜色] => 红色 [尺寸] => M [版本] => V2 ) [5] => Array ( [颜色] => 红色 [尺寸] => M [版本] => V3 ) [6] => Array ( [颜色] => 红色 [尺寸] => L [版本] => V1 ) [7] => Array ( [颜色] => 红色 [尺寸] => ...
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of The combination of php and sku is implemented using Cartesian product!. For more information, please follow other related articles on the PHP Chinese website!