用PHP组合数组,生成笛卡尔积。写几个例子

#创作灵感#

[红色,白色,黄色,蓝色]

[128G,256G,512G]

[国行,港版,美版,韩版]

用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);

这些示例会生成颜色、尺寸和版本的笛卡尔积,你可以根据需要自定义数组和维度来生成不同组合。

你可能感兴趣的:(php,android,开发语言)