JavaScript代码实现
/** * 组合多个数组 * @param {...Array} arrays * @returns */ function combine(...arrays) { let list = []; let helper = function (index, prev) { // 当前数组 let array = arrays[index]; // 是否为最后一个数组 let is_last = arrays.length - 1 == index; for (let item of array) { let current = prev.concat(item); if (is_last) { list.push(current); } else { helper(index + 1, current); } } }; helper(0, []); return list; } let names = ['iPhone X', 'iPhone XS']; let colors = ['黑色', '白色']; let storages = ['64g', '256g']; console.log(combine(names, colors, storages));
输出
[ [ 'iPhone X', '黑色', '64g' ], [ 'iPhone X', '黑色', '256g' ], [ 'iPhone X', '白色', '64g' ], [ 'iPhone X', '白色', '256g' ], [ 'iPhone XS', '黑色', '64g' ], [ 'iPhone XS', '黑色', '256g' ], [ 'iPhone XS', '白色', '64g' ], [ 'iPhone XS', '白色', '256g' ] ]
PHP实现版
<?php function helper($index, $prev, $arrays, & $list) { // 当前数组 $array = $arrays[$index]; // 是否为最后一个数组 $is_last = count($arrays) - 1 == $index; foreach ($array as $item) { $current = $prev; $current[] = $item; if ($is_last) { $list[] = $current; } else { helper($index + 1, $current, $arrays, $list); } } } function combine(...$arrays) { $list = []; helper(0, [], $arrays, $list); return $list; } $names = ['iPhone X', 'iPhone XS']; $colors = ['黑色', '白色']; $storages = ['64g', '256g']; echo json_encode(combine($names, $colors, $storages), JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
输出结果
[ ["iPhone X", "黑色", "64g"], ["iPhone X", "黑色", "256g"], ["iPhone X", "白色", "64g"], ["iPhone X", "白色", "256g"], [ "iPhone XS", "黑色", "64g"], [ "iPhone XS", "黑色", "256g"], [ "iPhone XS", "白色", "64g"], [ "iPhone XS", "白色", "256g"] ]