获取二维数组中所有元素的组合 (866 views)

gHOST

2020-05-12 11:26:55

    $arr = [
        ['1', '2', '3'],
        ['a', 'b', 'c'],
        ['A', 'B', 'C', 'D'],
    ];

    $result = [];
    foreach ($arr as $a) {
        $result = foo($result, $a);
    }

    dump($result);

    function foo($r, $arr)
    {
        $result = [];
        if (!$r) {
            foreach ($arr as $vv) {
                $result[] = $vv;
            }
        }

        foreach ($r as $v) {
            foreach ($arr as $vv) {
                $result[] = $v . ',' . $vv;
            }
        }

        return $result;
    }

结果

array:36 [▼
  0 => "1,a,A"
  1 => "1,a,B"
  2 => "1,a,C"
  3 => "1,a,D"
  4 => "1,b,A"
  5 => "1,b,B"
  6 => "1,b,C"
  7 => "1,b,D"
  8 => "1,c,A"
  9 => "1,c,B"
  10 => "1,c,C"
  11 => "1,c,D"
  12 => "2,a,A"
  13 => "2,a,B"
  14 => "2,a,C"
  15 => "2,a,D"
  16 => "2,b,A"
  17 => "2,b,B"
  18 => "2,b,C"
  19 => "2,b,D"
  20 => "2,c,A"
  21 => "2,c,B"
  22 => "2,c,C"
  23 => "2,c,D"
  24 => "3,a,A"
  25 => "3,a,B"
  26 => "3,a,C"
  27 => "3,a,D"
  28 => "3,b,A"
  29 => "3,b,B"
  30 => "3,b,C"
  31 => "3,b,D"
  32 => "3,c,A"
  33 => "3,c,B"
  34 => "3,c,C"
  35 => "3,c,D"
]
Tags: php 数组 组合