php 的一个算法问题

WBOY
Release: 2016-06-23 13:50:55
Original
981 people have browsed it

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

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

叫做 笛卡尔积

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!