日期:2014-05-17 浏览次数:20510 次
$arr=array('裤子','牛仔','纯棉','低腰','加肥'); for($i=1,$count=count($arr);$i<=$count;$i++) $temp[$i]=getCombinationToString($arr,$i); print_r($temp); function getCombinationToString($arr,$m){ $result = array(); if ($m ==1) return $arr; if ($m == count($arr)){ $result[] = implode('' , $arr); return $result; } $temp_firstelement = $arr[0]; unset($arr[0]); $arr = array_values($arr); $temp_list1 = getCombinationToString($arr, ($m-1)); foreach ($temp_list1 as $s){ $s = $temp_firstelement.$s; $result[] = $s; } $temp_list2 = getCombinationToString($arr, $m); foreach ($temp_list2 as $s){ $result[] = $s; } return $result; } /*Array ( [1] => Array ( [0] => 裤子 [1] => 牛仔 [2] => 纯棉 [3] => 低腰 [4] => 加肥 ) [2] => Array ( [0] => 裤子牛仔 [1] => 裤子纯棉 [2] => 裤子低腰 [3] => 裤子加肥 [4] => 牛仔纯棉 [5] => 牛仔低腰 [6] => 牛仔加肥 [7] => 纯棉低腰 [8] => 纯棉加肥 [9] => 低腰加肥 ) [3] => Array ( [0] => 裤子牛仔纯棉 [1] => 裤子牛仔低腰 [2] => 裤子牛仔加肥 [3] => 裤子纯棉低腰 [4] => 裤子纯棉加肥 [5] => 裤子低腰加肥 [6] => 牛仔纯棉低腰 [7] => 牛仔纯棉加肥 [8] => 牛仔低腰加肥 [9] => 纯棉低腰加肥 ) [4] => Array ( [0] => 裤子牛仔纯棉低腰 [1] => 裤子牛仔纯棉加肥 [2] => 裤子牛仔低腰加肥 [3] => 裤子纯棉低腰加肥 [4] => 牛仔纯棉低腰加肥 ) [5] => Array ( [0] => 裤子牛仔纯棉低腰加肥 ) )*/
------解决方案--------------------
组合问题,可参考
/**C(M,N) recursive*/ function C($m,$n) { if( $n <= 1) return $m; $rs = array(); while(count($m)) { $first = array_shift( $m ); foreach(C($m,$n-1) as $v) $rs[] = $first.$v; } return $rs; } $array = array('裤子','牛仔','纯棉','低腰','加肥'); while(count($array)) { for($i = 2,$j = count($array);$i <= $j;$i++) { print_r(C($array,$i)); } array_shift($array); }