在做商品属性时设计到多个属性直接参数的组合,因此用到了笛卡尔积这个概念。主要函数原理是利用递归的原理和求两个数组的笛卡尔积。
首先是数组结构,如下:也可以根据实际情况修改为$a = Array();$b=Array();即可。
array (size=2)所涉及到的两个函数
0 =>
array (size=2)
0 => string '48' (length=2)
1 => string '49' (length=2)
1 =>
array (size=3)
0 => string '51' (length=2)
1 => string '52' (length=2)
2 => string '53' (length=2)
//递归求笛卡尔积函数
public function combineDika($dikad,$dalen)
{
$data = $dikad;
$cnt = $dalen;
$result = array();
foreach($data[0] as $item) {
$result[] = array($item);
}
for($i = 1; $i < $cnt; $i++) {
$result = $this->combineArray($result,$data[$i]);
}
return $result;
}
//求两个数组的笛卡尔积
function combineArray($arr1,$arr2)
{
$result = array();
foreach ($arr1 as $item1) {
foreach ($arr2 as $item2) {
$temp = $item1;
$temp[] = $item2;
$result[] = $temp;
}
}
return $result;
}
运行结果:
array (size=6)
0 =>
array (size=2)
0 => string '48' (length=2)
1 => string '51' (length=2)
1 =>
array (size=2)
0 => string '48' (length=2)
1 => string '52' (length=2)
2 =>
array (size=2)
0 => string '48' (length=2)
1 => string '53' (length=2)
3 =>
array (size=2)
0 => string '49' (length=2)
1 => string '51' (length=2)
4 =>
array (size=2)
0 => string '49' (length=2)
1 => string '52' (length=2)
5 =>
array (size=2)
0 => string '49' (length=2)
1 => string '53' (length=2)