PHP输出多个元素的排列组合_PHP教程
程序员文章站
2022-03-31 20:01:07
...
解决问题:求一个含有N个元素的数组中取出M个元素组成新的数组,一共可以组合成的数组并输出
[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
$s = $arr[$i];
$ret = getCombinationToString(array_values($tmpArr), ($m-1), $result);
foreach($ret as $row) {
$result[] = $s . $row;
}
}
return $result;
}
?>
[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
$ret = getCombinationToString(array_values($tmpArr), ($m-1), $result);
foreach($ret as $row) {
$result[] = $s . $row;
}
}
return $result;
}
?>