1 下面的代码来生成笛卡尔积:
php
function cartesianProduct($arrays) {
$result = [[]];
foreach ($arrays as $property => $property_values) {
$tmp = [];
foreach ($result as $result_item) {
foreach ($property_values as $property_value) {
$tmp[] = array_merge($result_item, [$property => $property_value]);
}
}
$result = $tmp;
}
return $result;
}
$colors = ["红色", "白色", "黄色", "蓝色"];
$sizes = ["128G", "256G", "512G"];
$versions = ["国行", "港版", "美版", "韩版"];
// 生成笛卡尔积
$combinations = cartesianProduct([
'颜色' => $colors,
'尺寸' => $sizes,
'版本' => $versions
]);
// 输出笛卡尔积结果
foreach ($combinations as $combination) {
echo implode(', ', $combination) . "\n";
}
这段代码会生成由输入数组的笛卡尔积组成的数组。你可以根据需要修改输入数组,并按照相同的格式来调用cartesianProduct
函数。
2 下面是使用嵌套循环生成笛卡尔积的PHP代码示例:
php
// 定义多个数组
$colors = ['红色', '白色', '黄色', '蓝色'];
$capacities = ['128G', '256G', '512G'];
$versions = ['国行', '港版', '美版', '韩版'];
// 初始化笛卡尔积数组
$cartesianProduct = [];
// 使用嵌套循环生成笛卡尔积
foreach ($colors as $color) {
foreach ($capacities as $capacity) {
foreach ($versions as $version) {
$cartesianProduct[] = [$color, $capacity, $version];
}
}
}
// 打印笛卡尔积
foreach ($cartesianProduct as $combination) {
echo implode(', ', $combination) . "\n";
}
这将生成颜色、容量和版本的所有可能组合。你可以根据需要修改数组的值和数量来生成不同的笛卡尔积。此外,你还可以使用递归来处理不定数量的数组生成笛卡尔积。
3以下是一个示例,生成给定数组的笛卡尔积:
php
function cartesianProduct($arrays) {
$result = array();
$max = count($arrays) - 1;
$result = array();
function helper($arr, $i) {
global $result, $max;
if ($i == $max) {
foreach ($arr[$i] as $value) {
$result[] = $value;
}
} else {
foreach ($arr[$i] as $value) {
helper($arr, $i + 1);
foreach ($result as &$product) {
$product = "$product, $value";
}
}
}
}
helper($arrays, 0);
return $result;
}
// 示例用法
$colors = ["红色", "白色", "黄色", "蓝色"];
$storage = ["128G", "256G", "512G"];
$versions = ["国行", "港版", "美版", "韩版"];
$arrays = [$colors, $storage, $versions];
$cartesianProduct = cartesianProduct($arrays);
foreach ($cartesianProduct as $combination) {
echo "组合: $combination\n";
}
这个示例将生成给定数组的笛卡尔积,以获取所有可能的组合。你可以根据你的需求替换 $colors
、$storage
和 $versions
数组来生成不同的组合。
4 使用嵌套的循环来生成这些数组的笛卡尔积。以下是一些示例代码:
php
// 示例1:生成颜色和尺寸的笛卡尔积
$colors = ["红色", "白色", "黄色", "蓝色"];
$sizes = ["128G", "256G", "512G"];
$combinations = [];
foreach ($colors as $color) {
foreach ($sizes as $size) {
$combinations[] = [$color, $size];
}
}
print_r($combinations);
// 示例2:生成颜色、尺寸和版本的笛卡尔积
$colors = ["红色", "白色", "黄色", "蓝色"];
$sizes = ["128G", "256G", "512G"];
$versions = ["国行", "港版", "美版", "韩版"];
$combinations = [];
foreach ($colors as $color) {
foreach ($sizes as $size) {
foreach ($versions as $version) {
$combinations[] = [$color, $size, $version];
}
}
}
print_r($combinations);
这些示例会生成颜色、尺寸和版本的笛卡尔积,你可以根据需要自定义数组和维度来生成不同组合。