我有以下PHP代码,它可以解决一组数组中可能的组合:
function showCombinations($string, $traits, $i){
if($i >= count($traits)){
echo trim($string) . '<br>';
}else{
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
showCombinations('', $traits, 0);
Run Code Online (Sandbox Code Playgroud)
但是,我的问题是我需要将结果存储在一个数组中以便稍后处理,而不是只打印出来但我不知道如何在不使用全局变量的情况下完成此操作.
有没有人知道另一种方法来实现类似的东西或修改这个给我我可以使用的结果?
Luk*_*ský 11
归还他们.请showCombinations()返回的项目列表.在第一种情况下,您只返回一个项目,在另一个递归情况下,您返回一个列表,其中包含所有返回的列表.例如:
function showCombinations(...) {
$result = array();
if (...) {
$result[] = $item;
}
else {
foreach (...) {
$result = array_merge($result, showCombinations(...));
}
}
return $result;
}
Run Code Online (Sandbox Code Playgroud)