【PHP】二维数组数组实现笛卡尔积,即排列组合
PHP二维数组数组实现笛卡尔积,即排列组合:
https://www.jb51.net/article/144708.htm
//计算sku的笛卡儿积 public static function CartesianProduct($category,$type='/') {//$category,二维数组 [['绿色'=>12,'红色'=>13,'蓝色'=>14],['男'=>101,'女'=>89],['L'=>2011,'M'=>299]] $arr1 = []; $result = array_shift($category); while ($arr2 = array_shift($category)) { $arr1 = $result; $result = []; foreach ($arr1 as $k1=>$v1) { foreach ($arr2 as $k2=>$v2) { $result[$k1.'#'.$k2] = $v1.$type.$v2; } } } return $result; }
function
cartesian(
$arr
,
$str
=
array
()){
//去除第一个元素
$first
=
array_shift
(
$arr
);
//判断是否是第一次进行拼接
if
(
count
(
$str
) > 1) {
foreach
(
$str
as
$k
=>
$val
) {
foreach
(
$first
as
$key
=>
$value
) {
//最终实现的格式 1,3,76
//可根据具体需求进行变更
$str2
[] =
$val
.
','
.
$value
;
}
}
}
else
{
foreach
(
$first
as
$key
=>
$value
) {
//最终实现的格式 1,3,76
//可根据具体需求进行变更
$str2
[] =
$value
;
}
}
//递归进行拼接
if
(
count
(
$arr
) > 0){
$str2
= cartesian(
$arr
,
$str2
);
}
//返回最终笛卡尔积
return
$str2
;
}