PHP:找到“最合适的”

时间:2018-07-24 07:20:11

标签: php algorithm sorting

我需要将$quantities放入$sections中,以便不遗余力。

product_id 1 不能与 product_id 2 放在同一部分。

$quantities的总和始终等于或小于$sections的总和。

$sections$quantities数组当前按 volume 的顺序排列,从最低到最高。但是,如果您的解决方案要求更改,则可以更改。

我尝试一次用一个数量循环每个部分,但这导致第一个数量进入前4个部分,因此每个部分的体积为14000,但其中的数量为13000。

$quantities = array(
    0 => array(
        'volume' => '13000',
        'product_id' => '2'
    ),
    1 => array(
        'volume' => '24000',
        'product_id' => '1'
    )
);


$sections = array(
    44 => array(
        'id' => '44',
        'volume' => '2000.00'
    ),
    41 => array(
        'id' => '41',
        'volume' => '3000.00'
    ),
    45 => array(
        'id' => '45',
        'volume' => '4000.00'
    ),
    46 => array(
        'id' => '46',
        'volume' => '5000.00'
    ),
    48 => array(
        'id' => '48',
        'volume' => '5000.00'
    ),
    42 => array(
        'id' => '42',
        'volume' => '5000.00'
    ),
    43 => array(
        'id' => '43',
        'volume' => '6000.00'
    ),
    47 => array(
        'id' => '47',
        'volume' => '7000.00'
    )
);

例如,输出应如下所示:

   $output = array(
        0 => array(
            'section_id' => 43,
            'volume' => 6000,
            'product_id' => 2
        ),
        1 => array(
            'section_id' => 47,
            'volume' => 7000,
            'product_id' => 2
        ),
        2 => array(
            'section_id' => '44',
            'volume' => 2000,
            'product_id' => 1
        ),
        3 => array(
            'section_id' => '41',
            'volume' => 3000,
            'product_id' => 1
        ),
        4 => array(
            'section_id' => '45',
            'volume' => 4000,
            'product_id' => 1
        ),
        5 => array(
            'section_id' => '46',
            'volume' => 5000,
            'product_id' => 1
        ),
        6 => array(
            'section_id' => '48',
            'volume' => 5000,
            'product_id' => 1
        ),
        7 => array(
            'section_id' => '42',
            'volume' => 5000,
            'product_id' => 1
        ),
    );

0 个答案:

没有答案