PHP求一个含有N个元素的数组中取出M个元素组成新的数组,一共可以组合成的数组并输出

  • A+
所属分类:PHP日常 数组
<?php
$arr = array('a','b','c','d');
$result = array();
$t = getCombinationToString($arr, 4);
print_r($t);
 
function getCombinationToString($arr, $m) {
	if ($m ==1) {
	   return $arr;
	}
	$result = array();
	
	$tmpArr = $arr;
	unset($tmpArr[0]);
	for($i=0;$i<count($arr);$i++) {
		$s = $arr[$i];
		$ret = getCombinationToString(array_values($tmpArr), ($m-1), $result);
		
		foreach($ret as $row) {
			$result[] = $s . $row;
		}
	}
    
    return $result;
}
?>
结果


Array
(
    [0] => abcd
    [1] => abdd
    [2] => accd
    [3] => acdd
    [4] => adcd
    [5] => addd
    [6] => bbcd
    [7] => bbdd
    [8] => bccd
    [9] => bcdd
    [10] => bdcd
    [11] => bddd
    [12] => cbcd
    [13] => cbdd
    [14] => cccd
    [15] => ccdd
    [16] => cdcd
    [17] => cddd
    [18] => dbcd
    [19] => dbdd
    [20] => dccd
    [21] => dcdd
    [22] => ddcd
    [23] => dddd
)

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: