数组组合计算所有的组合形式?

array(2) {
  [0] => array(3) {
    [0] => string(3) "16G"
    [1] => string(3) "32G"
    [2] => string(3) "64G"
  }
  [1] => array(2) {
    [0] => string(1) "L"
    [1] => string(2) "XL"
  }
}

计算所有组合
['16G','L']
['16G','XL']
['32G','L']
['32G','XL']
['64G','L']
['64G','XL']
应该怎么组合成这样的结果
array(6) {
  [0] => array(3) {
    [0] => string(3) "16G"
    [1] => string(3) "L"
  }
  [1] => array(3) {
    [0] => string(3) "16G"
    [1] => string(3) "XL"
  }
  [2] => array(3) {
    [0] => string(3) "32G"
    [1] => string(3) "L"
  }
  [3] => array(3) {
    [0] => string(3) "32G"
    [1] => string(3) "XL"
  }
  [4] => array(3) {
    [0] => string(3) "64G"
    [1] => string(3) "L"
  }
  [5] => array(3) {
    [0] => string(3) "64G"
    [1] => string(3) "XL"
  }
 }
慕森卡
浏览 546回答 4
4回答

holdtom

把我在js版本答案里代码改成了php版如下 $input = [["16G", "32G", "64G"], ["L", "XL"]]; $output = array_reduce($input, function($result, $cross_item){ if(!$result){ return array_map(function($item){ return [$item]; }, $cross_item); } return array_reduce($cross_item, function($acc, $target) use ($result){ return array_merge($acc, array_map(function($result_item) use ($target){ $result_item[] = $target; return $result_item; }, $result)); }, []); }, []);

慕勒3428872

矩阵乘法 ? 算法导论之js实现--n×n矩阵计算

米琪卡哇伊

$arr = [["16G","32G","64G"],["L","XL"]]; $res = []; for($i=0;$i<count($arr[0]);$i++){ for($j=0;$j<count($arr[1]);$j++){ $tem = []; $tem[] = $arr[0][$i]; $tem[] = $arr[1][$j]; if($tem){ $res[] = $tem; } } } var_dump($res);

小唯快跑啊

如果不需要管顺序,只需要结果,可以用位运算,来进行全组合。 var rt=[]; const arr= [["16G", "32G", "64G"], ["L", "XL"]]; for(let i=0;i<8;i++){ let a1=i & 3;//取低2位 if(a1>2) continue; let a2=i>>2; let t=[arr[0][a1],arr[1][a2]]; rt.push(t); }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java