从多个嵌套数组中获取所有组合

won*_*nza 6 php arrays algorithm logic

我试图在PHP中提出一个算法来获取嵌套数组的所有组合:

Array
(
    [0] => Array
        (
            [0] => Option Object
                (
                    [strValue] => rough
                )

            [1] => Option Object
                (
                    [strValue] => smooth
                )

            [2] => Option Object
                (
                    [strValue] => coarse
                )

        )

    [1] => Array
        (
            [0] => Option Object
                (
                    [strValue] => shiney
                )

            [1] => Option Object
                (
                    [strValue] => mat
                )

        )

    [2] => Array
        (
            [0] => Option Object
                (
                    [strValue] => Large
                )

            [1] => Option Object
                (
                    [strValue] => Medium
                )

            [2] => Option Object
                (
                    [strValue] => Small
                )

            [3] => Option Object
                (
                    [strValue] => very large
                )

        )

)
Run Code Online (Sandbox Code Playgroud)

所以我会得到一些回报:

- ,闪耀,大

- ,闪耀,小

- ,闪耀,中等

- ,闪耀,非常大

- 光滑,光泽,大

- 光滑,闪亮,小巧

- 光滑,光泽,中等

- 光滑,光泽,非常大

等(在这个例子中应该是24)

我已经尝试了各种foreach示例和一些基本的递归函数,但我似乎没有快速到位.如果有人能给出如何解决这个问题的基本概要,我将非常感激,谢谢!

red*_*dow 8

我刚写了这个,适用于任何长度的数组..

<?php

function cartesian_product($a) {
  $result = array(array());
  foreach ($a as $list) {
    $_tmp = array();
    foreach ($result as $result_item) {
      foreach ($list as $list_item) {
        $_tmp[] = array_merge($result_item, array($list_item));
      }
    }
    $result = $_tmp;
  }
  return $result;
}


// Let's test this..                                                                                                                                                                                    

header('Content-type: text/plain');

$a = array(
  array('rough','smooth','coarse'),
  array('shiney','mat'),
  array('small','medium','large','x-large'),
);

$result = cartesian_product($a);
foreach ($result as $row) {
  print implode(", ", $row) ."\n";
}
Run Code Online (Sandbox Code Playgroud)

编辑:改进了一下代码..