PHP获取所有组合商品属性组成的数组
组合商品,获取每一种组合的结果。代码如下
private $models=[['RED','BLUE','GREEN'],['低配','中配','高配'],['进口','国产']];
private $index=0;
/**
* 组合
*/
public function combineAttributes(){
$m_len=count($this->models);
if($m_len>=2){
$result=$this->recurse($this->models[$this->index],$this->models[++$this->index],$m_len);
}else{
$result=$this->models[0];
}
print_r($result);
}
/**
* 递归拼接属性
* @param $array1
* @param $array2
* @param $m_len
* @return array
*/
public function recurse($array1,$array2,$m_len){
$res=[];
foreach ($array1 as $a1){
foreach ($array2 as $a2){
array_push($res,$a1.'-'.$a2);
}
}
$this->index++;
if($this->index<=$m_len-1){
return $this->recurse($res,$this->models[$this->index],$m_len);
}else{
return $res;
}
}
打印结果如下
Array
(
[0] => RED-低配-进口
[1] => RED-低配-国产
[2] => RED-中配-进口
[3] => RED-中配-国产
[4] => RED-高配-进口
[5] => RED-高配-国产
[6] => BLUE-低配-进口
[7] => BLUE-低配-国产
[8] => BLUE-中配-进口
[9] => BLUE-中配-国产
[10] => BLUE-高配-进口
[11] => BLUE-高配-国产
[12] => GREEN-低配-进口
[13] => GREEN-低配-国产
[14] => GREEN-中配-进口
[15] => GREEN-中配-国产
[16] => GREEN-高配-进口
[17] => GREEN-高配-国产
)
此代码参考其他博友的博客:https://shenchuochuo.iteye.com/blog/2306646
对此表示感谢!