PHP交叉排列的组合算法
warning:
这篇文章距离上次修改已过1066天,其中的内容可能已经有所变动。
应用场景商城类多规格组合如:
['红色','白色','蓝色','黑色']
['S','M','L','XL','XXL']
需要得到能有多少种组合
$combine_array = [['红色','白色','蓝色','黑色'],['S','M','L','XL','XXL']]
// 交叉排列的组合算法
protected function combine($array)
{
$heads = $array[0];
for ($i = 1; $i < count($array); $i++){
if (count($array[$i])){
$heads = $this->addNewType($heads, $array[$i]);
}
}
return $heads;
}
protected function addNewType($heads, $choices)
{
$result = [];
for ($i = 0; $i < count($heads); $i++){
for ($j = 0; $j < count($choices); $j++){
$result[] = $heads[$i] . ':' . $choices[$j];
}
}
return $result;
}