当前位置:Gxlcms > PHP教程 > PHP多个数组的排列组合,该如何解决

PHP多个数组的排列组合,该如何解决

时间:2021-07-01 10:21:17 帮助过:17人阅读

PHP 多个数组的排列组合
http://ask.csdn.net/questions/148636
------解决方案--------------------
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;
}
$ar = array(
array(1,2,3,4),
array('a','b','c'),
);
print_r(foo($ar));


Array
(
[0] => Array
(
[0] => 1
[1] => a
)

[1] => Array
(
[0] => 1
[1] => b
)

[2] => Array
(
[0] => 1
[1] => c
)

[3] => Array
(
[0] => 2
[1] => a
)

[4] => Array
(
[0] => 2
[1] => b
)

[5] => Array
(
[0] => 2
[1] => c
)

[6] => Array
(
[0] => 3
[1] => a
)

[7] => Array
(
[0] => 3
[1] => b
)

[8] => Array
(
[0] => 3
[1] => c
)

[9] => Array
(
[0] => 4
[1] => a
)

[10] => Array
(
[0] => 4
[1] => b
)

[11] => Array
(
[0] => 4
[1] => c
)

)


------解决方案--------------------
引用:
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));

人气教程排行