有个需求是差不多数学组合。
如1 2 3,2个数字为一个组合,可以组合多少种不同的情况。
结果要求为
1 2
1 3
-
2 3
这三种情况
function combination($array, $length) {
$result = [];
//取出数据要求总长度不符合 则直接返回空数组
$number = count($array);
if ($length <= 0 || $length > $number) {
return $result;
}
//循环开始
foreach ($array as $key => $value) {
$temp = [ $value ];
if ($length == 1) { //如果长度为了 则直接返回所有数据单个值组成的数组
$result[] = $temp;
} else {
//从当前值开始向后截取数组
$less = array_slice($array, $key + 1);
$small = combination($less, $length - 1);
foreach ($small as $smallValue) {
$result[] = array_merge($temp, $smallValue);
}
}
}
return $result;
}
$array = range(1,5);
combination($array,3);
打印结果
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 4
)
[2] => Array
(
[0] => 1
[1] => 2
[2] => 5
)
[3] => Array
(
[0] => 1
[1] => 3
[2] => 4
)
[4] => Array
(
[0] => 1
[1] => 3
[2] => 5
)
[5] => Array
(
[0] => 1
[1] => 4
[2] => 5
)
[6] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
[7] => Array
(
[0] => 2
[1] => 3
[2] => 5
)
[8] => Array
(
[0] => 2
[1] => 4
[2] => 5
)
[9] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
)