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"
}
}
4 回答
holdtom
TA贡献1805条经验 获得超10个赞
把我在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));
}, []);
}, []);
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
$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);
小唯快跑啊
TA贡献1863条经验 获得超2个赞
如果不需要管顺序,只需要结果,可以用位运算,来进行全组合。
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);
}
添加回答
举报
0/150
提交
取消