最近在做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));