PHP
<?php
function f(&$r, $t, $a, $n)
{
if ($n == 0) {
if (count($t)) {
$r[] = $t;
}
} else {
$count = count($a[$n - 1]);
for ($i = 0; $i < $count; $i++) {
f($r, array_merge($t, [$a[$n-1][$i]]), $a, $n - 1);
}
}
}
function combine($arr)
{
$r = [];
f($r, [], $arr, count($arr));
return $r;
}
$arr = [
[1, 2],
[3, 4],
];
print_r(combine($arr));
// preview
Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 3
[1] => 2
)
[2] => Array
(
[0] => 4
[1] => 1
)
[3] => Array
(
[0] => 4
[1] => 2
)
)
Javascript
function combine(arr) {
var r = [];
(function f(t, a, n) {
if (n == 0) return t.length ? r.push(t) : r;
for (var i = 0; i < a[n-1].length; i++) {
f(t.concat(a[n-1][i]), a, n - 1);
}
})([], arr, arr.length);
return r;
}
var arr = [
['1', '2'],
['3', '4']
];
var res = combine(arr);
console.log(res);
// preview
[["3","1"],["3","2"],["4","1"],["4","2"]]