递归计算笛卡尔乘积
如果使用
laravel
的话,直接使用collect
的crossJoin
方法也可以实现
代码如下
<?php
/**
* 递归计算笛卡尔乘积
*
* Created by PhpStorm.
* User: Alex
* Date: 2020/3/5
* Time: 20:35
*/
namespace App\Handlers;
class CarteSianHandler
{
/**
* 保存结果
*
* @var array
*/
public $products = [];
/**
* 计算笛卡尔乘积的结果
*
* @param array $params
* @param array $temporary
*/
public function carteSian(array $params, array $temporary = [])
{
foreach (array_shift($params) as $param) {
array_push($temporary, $param);
$params ? $this->carteSian($params, $temporary) : array_push($this->products, $temporary);
array_pop($temporary);
}
}
}
使用
$params = [
['颜色_黑色', '颜色_白色', '颜色_咖啡色'],
['尺寸_S', '尺寸_M', '尺寸_L'],
['材质_羽绒', '材质_鹅绒']
];
$cartSian = new CarteSian();
$cartSian->carteSian($params);
print_r($cartSian->products);
返回结果
array:18 [
0 => array:3 [
0 => "颜色_黑色"
1 => "尺寸_S"
2 => "材质_羽绒"
]
1 => array:3 [
0 => "颜色_黑色"
1 => "尺寸_S"
2 => "材质_鹅绒"
]
2 => array:3 [
0 => "颜色_黑色"
1 => "尺寸_M"
2 => "材质_羽绒"
]
3 => array:3 [
0 => "颜色_黑色"
1 => "尺寸_M"
2 => "材质_鹅绒"
]
4 => array:3 [
0 => "颜色_黑色"
1 => "尺寸_L"
2 => "材质_羽绒"
]
5 => array:3 [
0 => "颜色_黑色"
1 => "尺寸_L"
2 => "材质_鹅绒"
]
6 => array:3 [
0 => "颜色_白色"
1 => "尺寸_S"
2 => "材质_羽绒"
]
7 => array:3 [
0 => "颜色_白色"
1 => "尺寸_S"
2 => "材质_鹅绒"
]
8 => array:3 [
0 => "颜色_白色"
1 => "尺寸_M"
2 => "材质_羽绒"
]
9 => array:3 [
0 => "颜色_白色"
1 => "尺寸_M"
2 => "材质_鹅绒"
]
10 => array:3 [
0 => "颜色_白色"
1 => "尺寸_L"
2 => "材质_羽绒"
]
11 => array:3 [
0 => "颜色_白色"
1 => "尺寸_L"
2 => "材质_鹅绒"
]
12 => array:3 [
0 => "颜色_咖啡色"
1 => "尺寸_S"
2 => "材质_羽绒"
]
13 => array:3 [
0 => "颜色_咖啡色"
1 => "尺寸_S"
2 => "材质_鹅绒"
]
14 => array:3 [
0 => "颜色_咖啡色"
1 => "尺寸_M"
2 => "材质_羽绒"
]
15 => array:3 [
0 => "颜色_咖啡色"
1 => "尺寸_M"
2 => "材质_鹅绒"
]
16 => array:3 [
0 => "颜色_咖啡色"
1 => "尺寸_L"
2 => "材质_羽绒"
]
17 => array:3 [
0 => "颜色_咖啡色"
1 => "尺寸_L"
2 => "材质_鹅绒"
]
]