$array = [2,3,4,5];
我想要组数组元素,其中元素总和最多可以为5,并且要求尽可能少的组:
[
[2,3],
[4],
[5],
]
如何以编程方式进行分组
答案 0 :(得分:1)
我想你可以使用类似的东西:
$array = [2,3,4,5,3,1,3,5,2,2,8];
$results = [];
for( $x=0; $x < count($array); $x++ )
{
if( $x < count($array) - 1 ){
if ( $array[$x] + $array[$x + 1] <= 5 )
{
array_push( $results, [$array[$x], $array[$x + 1]] );
$x++;
} else if( $array[$x] <= 5 ){
array_push( $results, [$array[$x]] );
}
} else if( $array[$x] <= 5 ){
array_push( $results, [$array[$x]] );
}
}
输出:
Array
(
[0] => Array
(
[0] => 2
[1] => 3
)
[1] => Array
(
[0] => 4
)
[2] => Array
(
[0] => 5
)
[3] => Array
(
[0] => 3
[1] => 1
)
[4] => Array
(
[0] => 3
)
[5] => Array
(
[0] => 5
)
[6] => Array
(
[0] => 2
[1] => 2
)
)