PHP数组内容不重复组合排列算法

最近在做ecshop的商品库存模块,分别给一款商品的多个属性组合设置库存,如下图:

 

 一款手机有不同颜色,屏幕尺寸,系统和电量,都要设置不同的库存,如果都要手动选择属性组合,则会耗费很多不必要的时间。假如打开页面时就已经设置好属性排列组合那就最好不过,因此想了整天,写了如下函数:

 1 /*
 2 Author:GaZeon
 3 Date:2016-6-20
 4 Function:getArrSet
 5 Param:$arrs 二维数组
 6 getArrSet(array(array(),...))
 7 数组不重复排列集合
 8 */
 9 function getArrSet($arrs,$_current_index=-1)
10 {
11     //总数组
12     static $_total_arr;
13     //总数组下标计数
14     static $_total_arr_index;
15     //输入的数组长度
16     static $_total_count;
17     //临时拼凑数组
18     static $_temp_arr;
19     
20     //进入输入数组的第一层,清空静态数组,并初始化输入数组长度
21     if($_current_index<0)
22     {
23         $_total_arr=array();
24         $_total_arr_index=0;
25         $_temp_arr=array();
26         $_total_count=count($arrs)-1;
27         getArrSet($arrs,0);
28     }
29     else
30     {
31         //循环第$_current_index层数组
32         foreach($arrs[$_current_index] as $v)
33         {
34             //如果当前的循环的数组少于输入数组长度
35             if($_current_index<$_total_count)
36             {
37                 //将当前数组循环出的值放入临时数组
38                 $_temp_arr[$_current_index]=$v;
39                 //继续循环下一个数组
40                 getArrSet($arrs,$_current_index+1);
41                 
42             }
43             //如果当前的循环的数组等于输入数组长度(这个数组就是最后的数组)
44             else if($_current_index==$_total_count)
45             {
46                 //将当前数组循环出的值放入临时数组
47                 $_temp_arr[$_current_index]=$v;
48                 //将临时数组加入总数组
49                 $_total_arr[$_total_arr_index]=$_temp_arr;
50                 //总数组下标计数+1
51                 $_total_arr_index++;
52             }
53 
54         }
55     }
56     
57     return $_total_arr;
58 }
59 
60 /*************TEST**************/
61 $arr=array(
62     array('a','b','c'),
63     array('A','B','C'),
64     array('1','2','3'),
65     array('I','II','III')
66 );
67 
68 var_dump(getArrSet($arr));
原文地址:https://www.cnblogs.com/GaZeon/p/5602049.html