本文实例讲述了PHP实现数组的笛卡尔积运算。分享给大家供大家参考,具体如下:
数组的笛卡尔积在实际中还是挺有用处的,比如计算商品的规格时就经常用到,下面写一种实现方式,如下代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
$arr = array ( array (2), array (6,7), array ( 'a' , 'b' , 'c' ) ); function dikaer( $arr ){ $arr1 = array (); $result = array_shift ( $arr ); while ( $arr2 = array_shift ( $arr )){ $arr1 = $result ; $result = array (); foreach ( $arr1 as $v ){ foreach ( $arr2 as $v2 ){ if (! is_array ( $v )) $v = array ( $v ); if (! is_array ( $v2 )) $v2 = array ( $v2 ); $result [] = array_merge_recursive ( $v , $v2 ); } } } return $result ; } |
以上例子输出的结果如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
Array ( [0] => Array ( [0] => 2 [1] => 6 [2] => a ) [1] => Array ( [0] => 2 [1] => 6 [2] => b ) [2] => Array ( [0] => 2 [1] => 6 [2] => c ) [3] => Array ( [0] => 2 [1] => 7 [2] => a ) [4] => Array ( [0] => 2 [1] => 7 [2] => b ) [5] => Array ( [0] => 2 [1] => 7 [2] => c ) ) |
如果需要输出字符串形式的结果可以把代码改成这样
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
function dikaer( $arr ){ $arr1 = array (); $result = array_shift ( $arr ); while ( $arr2 = array_shift ( $arr )){ $arr1 = $result ; $result = array (); foreach ( $arr1 as $v ){ foreach ( $arr2 as $v2 ){ $result [] = $v . ',' . $v2 ; } } } return $result ; } |
输出结果如下所示:
1
2
3
4
5
6
7
8
9
|
Array ( [0] => 2,6,a [1] => 2,6,b [2] => 2,6,c [3] => 2,7,a [4] => 2,7,b [5] => 2,7,c ) |
希望本文所述对大家PHP程序设计有所帮助。
原文链接:http://blog.csdn.net/chenbalala/article/details/52618665