亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 86 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號