为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
忽然笑 2022-12-30 16:03:23
如何返回所有可能的组合 [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 loopsfor($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 loopsfor($i=0; $i<count($arr2); $i++){for($j=0; $j<count($arr1); $j++){$ret = $arr2[$i] . $arr1[$j]; array_push($result, $ret);}}//display the resultfor ($i = 0; $i < count($result); $i++){echo result([$i];}上面的代码运行良好。但是对于 5 项数组 [1,2,3,4,5],它需要大约(5 项 * 24 个循环)= 120 个循环。
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

如所见,您希望通过以下方式拆分2 strings into chars并获得所有组合2 chars:第一种形式blank1和第二种形式blank2。

而不是手动进行组合使用常规for-loop.


$result = array();

for ($i = 0; $i < count($blank1); $i++)

{

  for ($j = 0; $j < count($blank2); $j++)

  {

     //set combination

     $aux = $blank1[$i].$blank2[$j];

     array_push($result, $aux);

  }


}

//result should be populated with combination of 2

//just list it and use as need

for ($i = 0; $i < count($result); $i++)

{

   echo $result[$i];

}

//same with stored or checking on db : use loops

对于多个组合,使用更多的嵌套循环,

例如:[blank1][blank2][blank1]- 3 组合


$result = array();

//1

for ($i = 0; $i < count($blank1); $i++)

{

  //2

  for ($j = 0; $j < count($blank2); $j++)

  {

     //3

     for ($k = 0; $k < count($blank1); $k++)

     {

     //set combination

     $aux = $blank1[$i].$blank2[$j].$blank1[$k];

     array_push($result, $aux);

     }

   }


}


与您想要的任何数字相同!如果要写很多循环会有点烦人但请注意while can be used with an adequate algorithm。但目前只需尽可能简单并获得所需的结果。


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 114 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号