最大总和等于的PHP组数组项

时间:2017-04-20 16:01:51

标签: php arrays

$array = [2,3,4,5];

我想要组数组元素,其中元素总和最多可以为5,并且要求尽可能少的组:

[
[2,3],
[4],
[5],
]

如何以编程方式进行分组

1 个答案:

答案 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
        )

)

php example