How to get all possible combinations of multidimensional array [duplicate]

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

This question already has an answer here:

Okay, here I have a multidimensional array. It consists of 3 arrays each with 3 numbers.

$numbers = array(     array("1", "2", "3"),     array("4", "5", "6"),     array("7", "8", "9"), );

I want to generate and list every possible combination of the numbers from these arrays. So for example, "147" (1 being from the first array, 4 being from the second array and 7 being from the third array), "247, 347, 157, 257, 357, 167, 267, 367, etc..."

The important thing is that the first number must come from the first array, the second number from the second array and the third from the third array.

I have tried to loop through these arrays using nested foreach loops, but I can't quite figure it out and it's making my head spin. Hope that makes sense, any help would be greatly appreciated.

回答1:

<?php $numbers = array(     array("1", "2", "3"),     array("4", "5", "6"),     array("7", "8", "9"), );  for ($i=0;$i<3;$i++) {   for ($j=0;$j<3;$j++) {     for ($k=0;$k<3;$k++) {       echo $numbers[0][$i]+" "+$numbers[1][$j]+" "+$numbers[2][$k]+"\n";     }   } } ?>

I didn't program in php before so the code may make your eyes bleed. Nonetheless, the code works and demonstrates the idea.



回答2:

$numbers = array(     array("1", "2", "3"),     array("4", "5", "6"),     array("7", "8", "9"), );  $f_nb = $numbers['0']; $s_nb = $numbers['1']; $t_nb = $numbers['2'];  $final_array = array();  for($a = 0; $a<sizeof($f_nb); $a++)  {     for($b = 0; $b<sizeof($s_nb); $b++)      {         for($c = 0; $c<sizeof($t_nb); $c++)          {             $final_array[] = $f_nb["$a"] . $s_nb["$b"] . $t_nb["$c"];         }     } }  print_r($final_array);


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!