每个连接的多维数组

时间:2019-09-03 20:06:43

标签: php arrays

有一个像

这样的多维数组
  

[­ [“ 14”,“ 16”],[“ 26”],[“ 24”],[“ 5”,“ 8”]]

总数组的长度不受限制,嵌套将平均1-3个元素 嵌套的将始终是数字,而不是数组,即数组是二维的。任务是获得“每个人都有”的关系,即我应该获得这种类型的集合

  

14,26,24,5;   14,26,24,8;   16,26,24,5;   16,26,24,8;

我尝试了循环,并尝试了递归,但这不起作用。

你能帮我吗?

谢谢

1 个答案:

答案 0 :(得分:0)

$data = [
    [2, 4],
    [],
    [3, 6],
    [2, 3],
];

$output = array_reduce($data, function (array $carry = null, array $item = null): array {
    if (!$carry) {
        return $item;
    }

    if (!$item) {
        return $carry;
    }

    $output = [];
    foreach ($carry as $foo) {
        foreach ($item as $bar) {
            $output[] = $foo . '-' . $bar;
        }
    }

    return $output;
});

print_r($output);

输出:

Array
(
    [0] => 2-3-2
    [1] => 2-3-3
    [2] => 2-6-2
    [3] => 2-6-3
    [4] => 4-3-2
    [5] => 4-3-3
    [6] => 4-6-2
    [7] => 4-6-3
)