# php 多组数组算所有的组合形式

2019/04/27 11:02

颜色

红色、黄色


尺寸

M、L、XL


材质

轻、重


红色、M、轻  10元

...


// 颜色
$A = ['红色','黄色'];$B = ['M','L','XL'];
$C = ['轻','重'];  需要计算出这三个数组的组合方式 $res = array();
foreach($A as$ak=>$av){ foreach($B as $bk=>$bv)
{
foreach($C as$ck=>$cv) {$res[] = $av.'_'.$bv.'_'.$cv; } } }  查看结果。一共 2*3*2 12种组合方式 array(12) { [0] => string(12) "红色_M_轻" [1] => string(12) "红色_M_重" [2] => string(12) "红色_L_轻" [3] => string(12) "红色_L_重" [4] => string(13) "红色_XL_轻" [5] => string(13) "红色_XL_重" [6] => string(12) "黄色_M_轻" [7] => string(12) "黄色_M_重" [8] => string(12) "黄色_L_轻" [9] => string(12) "黄色_L_重" [10] => string(13) "黄色_XL_轻" [11] => string(13) "黄色_XL_重" }  但是由于属性属于不确定性，这种计算方式需要每一个属性一个循环不现实，所以需要改进代码 $A = ['红色','黄色'];
$B = ['M','L','XL'];$C = ['轻','重'];

// 先将各属性值处理成一个整体
$list['A'] =$A;
$list['B'] =$B;
$list['C'] =$C;

$res = array(); foreach ($list as $k =>$v) {
$res = getCombinationToString($v);
}

/**
* 获取组合的结果
* [@author](https://my.oschina.net/arthor) 18y
* @anotherdate 2019-04-27T09:49:44+0800
* [@param](https://my.oschina.net/u/2303379)       array                         $val 组合内容 * [@return](https://my.oschina.net/u/556800) [type] [description] */ function getCombinationToString($val)
{
// 保存上一个的值
static $res = array(); if(empty($res))
{
$res =$val;
}else{
// 临时数组保存结合的结果
$list = array(); foreach ($res as $k =>$v) {
foreach ($val as$key => $value) {$list[$k.'_'.$key] = $v.'_'.$value;
}
}
$res =$list;
}
return \$res;
}


array(12) {
["0_0_0"] => string(12) "红色_M_轻"
["0_0_1"] => string(12) "红色_M_重"
["0_1_0"] => string(12) "红色_L_轻"
["0_1_1"] => string(12) "红色_L_重"
["0_2_0"] => string(13) "红色_XL_轻"
["0_2_1"] => string(13) "红色_XL_重"
["1_0_0"] => string(12) "黄色_M_轻"
["1_0_1"] => string(12) "黄色_M_重"
["1_1_0"] => string(12) "黄色_L_轻"
["1_1_1"] => string(12) "黄色_L_重"
["1_2_0"] => string(13) "黄色_XL_轻"
["1_2_1"] => string(13) "黄色_XL_重"
}


id  name
1   颜色
2   尺寸
3   材质


id  attr_id attr_val
1    1      红色
2    1      黄色
3    2      M
4    2      L
...


3
2 收藏

3 评论
2 收藏
3