在 PHP 中组合和置换两个不同数组的项目

如何返回所有可能的组合 [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 个循环。


忽然笑
浏览 115回答 1
1回答

慕哥6287543

如所见,您希望通过以下方式拆分2 strings into chars并获得所有组合2 chars:第一种形式blank1和第二种形式blank2。而不是手动进行组合使用常规for-loop.$result = array();for ($i = 0; $i < count($blank1); $i++){&nbsp; for ($j = 0; $j < count($blank2); $j++)&nbsp; {&nbsp; &nbsp; &nbsp;//set combination&nbsp; &nbsp; &nbsp;$aux = $blank1[$i].$blank2[$j];&nbsp; &nbsp; &nbsp;array_push($result, $aux);&nbsp; }}//result should be populated with combination of 2//just list it and use as needfor ($i = 0; $i < count($result); $i++){&nbsp; &nbsp;echo $result[$i];}//same with stored or checking on db : use loops对于多个组合,使用更多的嵌套循环,例如:[blank1][blank2][blank1]- 3 组合$result = array();//1for ($i = 0; $i < count($blank1); $i++){&nbsp; //2&nbsp; for ($j = 0; $j < count($blank2); $j++)&nbsp; {&nbsp; &nbsp; &nbsp;//3&nbsp; &nbsp; &nbsp;for ($k = 0; $k < count($blank1); $k++)&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp;//set combination&nbsp; &nbsp; &nbsp;$aux = $blank1[$i].$blank2[$j].$blank1[$k];&nbsp; &nbsp; &nbsp;array_push($result, $aux);&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}}与您想要的任何数字相同!如果要写很多循环会有点烦人但请注意while can be used with an adequate algorithm。但目前只需尽可能简单并获得所需的结果。
打开App,查看更多内容
随时随地看视频慕课网APP