如何返回所有可能的组合 [12345]、[12354] 直至 [54312]、[54321],而不必运行 120 for...loop,就像在下面的代码中组合 2 项数组一样?
从给定数组 $word = [1,2] 返回所有可能的组合,
//break the array into 2 separate arrays
$arr1 = $word[0]; $arr2 = $word[1];
//computer for first array item...each item will have 2 loops
for($i=0; $i<count($arr1); $i++){
for($j=0; $j<count($arr2); $j++){
$ret = $arr1[$i] . $arr2[$j]; array_push($result, $ret);
}
}
//computer for second array item..each item will have 2 loops
for($i=0; $i<count($arr2); $i++){
for($j=0; $j<count($arr1); $j++){
$ret = $arr2[$i] . $arr1[$j]; array_push($result, $ret);
}
}
//display the result
for ($i = 0; $i < count($result); $i++){
echo result([$i];
}
上面的代码运行良好。
但是对于 5 项数组 [1,2,3,4,5],它需要大约(5 项 * 24 个循环)= 120 个循环。
忽然笑
慕哥6287543
随时随地看视频慕课网APP