如何获得多维阵列的所有可能的组合 [英] How to get all possible combinations of multidimensional array

查看:103
本文介绍了如何获得多维阵列的所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我在这里有一个多维数组。它由每个3阵列与3个数字。

  $号=阵列(
    阵列(1,2,3),
    阵列(4,5,6),
    阵列(7,8,9),
);

我要生成并列出从这些阵列数字的每一个可能的组合。因此,例如,147,247,347,157,257,357,167,267,367,等等(1从第一阵列,​​4从第二阵列是和7从第三阵列是为).. 。

重要的是,第一数目必须来自第一阵列,​​从所述第二阵列的第二数量,并从第三阵列的第三

我曾尝试通过使用嵌套foreach循环这些数组循环,但我不能完全弄清楚和它使我目瞪口呆。希望是有道理的,任何帮助将大大AP preciated。


解决方案

 < PHP
$数=阵列(
    阵列(1,2,3),
    阵列(4,5,6),
    阵列(7,8,9),
);为($ I = 0; $ I 3;; $ I ++){
  为($ J = 0; $ J&下; 3; $ J ++){
    为($ K = 0; $ K&下; 3; $ķ++){
      回声$号码[0] [$ i] ++ $号码[1] [$ J] ++ $号码[2] [$ K] +\\ n;
    }
  }
}
?>

我没有计划在PHP之前,以使code可让你的眼睛流血。尽管如此,code ++工程,并演示了这个想法。

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.

解决方案

<?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.

这篇关于如何获得多维阵列的所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆