Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:如何将数组值与动态数组数量的数组值合并?_Php_Arrays_Array Merge - Fatal编程技术网

PHP:如何将数组值与动态数组数量的数组值合并?

PHP:如何将数组值与动态数组数量的数组值合并?,php,arrays,array-merge,Php,Arrays,Array Merge,我想将一个数组的每个数组值与另一个数组的每个数组值合并。像这样: $a1 = ['a', 'b']; $a2 = ['c', 'd', 'e', 'f']; $a3 = ['g', 'h']; $result = []; foreach($a1 as $a) { foreach($a2 as $b) { foreach($a3 as $c) { $result[] = [$a, $b, $c]; } } } 结果应该如下

我想将一个数组的每个数组值与另一个数组的每个数组值合并。像这样:

$a1 = ['a', 'b'];
$a2 = ['c', 'd', 'e', 'f'];
$a3 = ['g', 'h'];
$result = [];

foreach($a1 as $a) {
    foreach($a2 as $b) {
        foreach($a3 as $c) {
            $result[] = [$a, $b, $c];
        }
    }
}
结果应该如下所示:

array(16) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "c"
    [2]=>
    string(1) "g"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "c"
    [2]=>
    string(1) "h"
  }
  .... 
}
但是我不知道如何动态地完成,因为数组的数量(例如$a1-$a3)也应该是动态的。因此,我可以合并例如$a1-$a6或$a1-$a2


我希望有人能帮助我。:)

对可变数组数的笛卡尔乘积使用以下递归函数:

function array_cartesian_product(...$array)
{
    if (empty($array)) return [[]];

    $column = array_shift($array);
    $cartesian = array_cartesian_product(...$array);

    $result = [];
    foreach ($column as $item) {
        foreach ($cartesian as $row) {
            array_unshift($row, $item);
            array_push($result, $row);
        }
    }
    return $result;        
}

// Usage:

$a1 = ['a', 'b'];
$a2 = ['c', 'd', 'e', 'f'];
$a3 = ['g', 'h'];

$result = array_cartesian_product($a1, $a2, $a3);

print_r($result);

$a = [ ['a', 'b'], ['c', 'd', 'e', 'f'], ['g', 'h'] ];

$result = array_cartesian_product(...$a);

print_r($result);

嗨,Remy,不是因为我得到了一个包含所有值的数组。但是我想要这样的东西:[[a,c,g],[a,c,h],[a,d,g |…]。当我按照你的答案做的时候,我得到了类似[a,b,c,d,e…],但这不是我想要的。谢谢你,这很有魅力,我学到了一些新的东西。:)