分享一个递归计算笛卡尔积的方法

``````namespace CarteSian;

class CarteSian
{

/**
* Store results
*
* @var array
*/
public \$products = [];

/**
* Calculate the Cartesian product
*
* @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);
}
}
}``````

``````\$cartSian = new CarteSian();

\$params = [
'Girls' => [
'雾岛董香',
'艾米莉娅',
'结城明日奈',
],
'Boys' => [
'金木研',
'菜月昴',
'桐谷和人',
],
'Hentais' => [
'华城绫女',
'培提尔其乌斯·罗马尼空提',
'月山习',
]
];

\$cartSian->carteSian(\$params);

print_r(\$cartSian->products);``````

``````Array
(
[0] => Array
(
[0] => 雾岛董香
[1] => 金木研
[2] => 华城绫女
)

[1] => Array
(
[0] => 雾岛董香
[1] => 金木研
[2] => 培提尔其乌斯·罗马尼空提
)

[2] => Array
(
[0] => 雾岛董香
[1] => 金木研
[2] => 月山习
)

[3] => Array
(
[0] => 雾岛董香
[1] => 菜月昴
[2] => 华城绫女
)

[4] => Array
(
[0] => 雾岛董香
[1] => 菜月昴
[2] => 培提尔其乌斯·罗马尼空提
)

[5] => Array
(
[0] => 雾岛董香
[1] => 菜月昴
[2] => 月山习
)

[6] => Array
(
[0] => 雾岛董香
[1] => 桐谷和人
[2] => 华城绫女
)

[7] => Array
(
[0] => 雾岛董香
[1] => 桐谷和人
[2] => 培提尔其乌斯·罗马尼空提
)

[8] => Array
(
[0] => 雾岛董香
[1] => 桐谷和人
[2] => 月山习
)

[9] => Array
(
[0] => 艾米莉娅
[1] => 金木研
[2] => 华城绫女
)

[10] => Array
(
[0] => 艾米莉娅
[1] => 金木研
[2] => 培提尔其乌斯·罗马尼空提
)

[11] => Array
(
[0] => 艾米莉娅
[1] => 金木研
[2] => 月山习
)

[12] => Array
(
[0] => 艾米莉娅
[1] => 菜月昴
[2] => 华城绫女
)

[13] => Array
(
[0] => 艾米莉娅
[1] => 菜月昴
[2] => 培提尔其乌斯·罗马尼空提
)

[14] => Array
(
[0] => 艾米莉娅
[1] => 菜月昴
[2] => 月山习
)

[15] => Array
(
[0] => 艾米莉娅
[1] => 桐谷和人
[2] => 华城绫女
)

[16] => Array
(
[0] => 艾米莉娅
[1] => 桐谷和人
[2] => 培提尔其乌斯·罗马尼空提
)

[17] => Array
(
[0] => 艾米莉娅
[1] => 桐谷和人
[2] => 月山习
)

[18] => Array
(
[0] => 结城明日奈
[1] => 金木研
[2] => 华城绫女
)

[19] => Array
(
[0] => 结城明日奈
[1] => 金木研
[2] => 培提尔其乌斯·罗马尼空提
)

[20] => Array
(
[0] => 结城明日奈
[1] => 金木研
[2] => 月山习
)

[21] => Array
(
[0] => 结城明日奈
[1] => 菜月昴
[2] => 华城绫女
)

[22] => Array
(
[0] => 结城明日奈
[1] => 菜月昴
[2] => 培提尔其乌斯·罗马尼空提
)

[23] => Array
(
[0] => 结城明日奈
[1] => 菜月昴
[2] => 月山习
)

[24] => Array
(
[0] => 结城明日奈
[1] => 桐谷和人
[2] => 华城绫女
)

[25] => Array
(
[0] => 结城明日奈
[1] => 桐谷和人
[2] => 培提尔其乌斯·罗马尼空提
)

[26] => Array
(
[0] => 结城明日奈
[1] => 桐谷和人
[2] => 月山习
)

)``````

Github地址 Seaony/CarteSian

《L05 电商实战》

《G01 Go 实战入门》

4年前 评论

1年前 评论