原始数据$ource=['1L','5W-40','到店安装'];
想要实现的结果:
方法如下
public function getCombineArrayByLength($source)
{
$result = [];
sort($source); //保证初始数组是有序的
$last = count($source) - 1; //$source尾部元素下标
$x = $last;
$count = 1; //组合个数统计
array_push($result, implode(',', $source));
// echo implode(',', $source), "<br>"; //输出第一种组合
while (true) {
$y = $x--; //相邻的两个元素
if ($source[$x] < $source[$y]) { //如果前一个元素的值小于后一个元素的值
$z = $last;
while ($source[$x] > $source[$z]) { //从尾部开始,找到第一个大于 $x 元素的值
$z--;
}
/* 交换 $x 和 $z 元素的值 */
list($source[$x], $source[$z]) = array($source[$z], $source[$x]);
/* 将 $y 之后的元素全部逆向排列 */
for ($i = $last; $i > $y; $i--, $y++) {
list($source[$i], $source[$y]) = array($source[$y], $source[$i]);
}
array_push($result, implode(',', $source));
// echo implode(',', $source), "<br>"; //输出组合
$x = $last;
$count++;
}
if ($x == 0) { //全部组合完毕
break;
}
}
return $result;
}
二维数组排列组合,在这个场景中,其实就是把多个属性的多个元素进行不重复的组合:,如:
使用计算机的解题思路,遍历所有属性,每次将一个属性的所有元素放入最终结果集中,并将结果作为模板,代入下一个属性计算中,代码如下
public function getTwoCombineArray($options){
$result=[];
foreach ($options as $k => $v) {
if(count($result)>0){
$clone= $result;//将第一列作为模板
$result=[];//置空当前列表,因为只有第一列的数据,组合是不完整的
//遍历当前列,追加到模板中,使模板中的组合变得完整
foreach ($v as $k1 => $v1) {
$temp=$clone;
foreach ($temp as $index => $value) {
$value[$k]=$v1;
$temp[$index]=$value;
}
//将完整的组合拼回到模板中
$result=array_merge($result,$temp);
}
}else{
//先计算出第一列
foreach ($v as $item) {
$result[][$k]= $item;
}
}
}
return $result;
}