Home  >  Article  >  Backend Development  >  php 的一个算法问题

php 的一个算法问题

WBOY
WBOYOriginal
2016-06-23 13:50:551030browse

有这样一个数组
$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        ))

感谢,这个算法叫什么名来的?

叫做 笛卡尔积

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn