从其他数组创建一个递归组合数组

时间:2017-05-15 07:25:08

标签: php arrays associative-array cartesian-product

我想从这些数组中走出来:

$array1 = ["x", "y", "z"];
$array2 = ["a","b"];
$array3 = ["1","2","3","4","5","6"];

到这个数组:

$arrayResult = 
array(
    array("x" => array("a" => array(1,2,3,4,5,6),
                       "b" => array(1,2,3,4,5,6)),
          "y" => array("a" => array(1,2,3,4,5,6),
                       "b" => array(1,2,3,4,5,6)),
          "z" => array("a" => array(1,2,3,4,5,6),
                       "b" => array(1,2,3,4,5,6)))
);

我试图用笛卡尔积的方法制作这个组合数组,但到目前为止还没有令人满意的结果。

2 个答案:

答案 0 :(得分:1)

这是另一种不使用任何循环的解决方案:

$array1 = ["x", "y", "z"];
$array2 = ["a","b"];
$array3 = ["1","2","3","4","5","6"];

$result = array_combine(
    $array1, 
    array_fill(
        0, 
        count($array1), 
        array_combine(
            $array2, 
            array_fill(0, count($array2), $array3)
        )
    )
);

print_r($result);

这是the demo

答案 1 :(得分:0)

使用array_fill_keys两次得到结果

$result = array_fill_keys(
              $array1, 
              array_fill_keys($array2,  $array3)
);

<强> Demo on eval.in