Home > Article > Backend Development > php 的一个算法问题
有这样一个数组
$arr = array(
array('a_1','a_2'),
array('b_1','b_2'),
array('c_1','c_2')
);
最后能计算成下面这个样子。
array(
'a_1,b_1,c_1',
'a_1,b_1,c_2',
'a_1,b_2,c_1',
'a_1,b_2,c_2',
'a_2,b_1,c_1',
'a_2,b_1,c_2',
'a_2,b_2,c_1',
'a_2,b_2,c_2',
);
就是让数组里的每一个元素和其他元素组合。
function foo($d) { $r = array_pop($d); while($d) { $t = array(); $s = array_pop($d); if(! is_array($s)) $s = array($s); foreach($s as $x) { foreach($r as $y) $t[] = array_merge(array($x), is_array($y) ? $y : array($y)); } $r = $t; } return $r;}$ary = array( 'a'=>array('a_1','a_2'), 'b'=>array('b_1','b_2'), 'c'=>array('c_1','c_2'),);print_r(foo($ary));
Array( [0] => Array ( [0] => a_1 [1] => b_1 [2] => c_1 ) [1] => Array ( [0] => a_1 [1] => b_1 [2] => c_2 ) [2] => Array ( [0] => a_1 [1] => b_2 [2] => c_1 ) [3] => Array ( [0] => a_1 [1] => b_2 [2] => c_2 ) [4] => Array ( [0] => a_2 [1] => b_1 [2] => c_1 ) [5] => Array ( [0] => a_2 [1] => b_1 [2] => c_2 ) [6] => Array ( [0] => a_2 [1] => b_2 [2] => c_1 ) [7] => Array ( [0] => a_2 [1] => b_2 [2] => c_2 ))
感谢,这个算法叫什么名来的?
叫做 笛卡尔积