Skip to content

Instantly share code, notes, and snippets.

@chrisbergr
Created June 5, 2020 07:28
Show Gist options
  • Save chrisbergr/2b5de486487fdab1caf92b3bdee92ac3 to your computer and use it in GitHub Desktop.
Save chrisbergr/2b5de486487fdab1caf92b3bdee92ac3 to your computer and use it in GitHub Desktop.
Search for most cost effective package combination (shipping)
<?php
function fill_packages( $packages ) {
$overrun = 42; // Items in cart
$cost = 0;
$filled = array();
$quantities = array();
foreach( $packages as $the_package ){
$delivers = floor( $overrun / $the_package['contain'] );
if( ! $delivers ) {
continue;
}
$filled[$the_package['name']] = $delivers;
$overrun = $overrun - ( $delivers * $the_package['contain'] );
$cost = $cost + ( $delivers * $the_package['cost'] );
}
if( $overrun ) {
return 'Error, Overrun of ' . $overrun . '!';
}
return array(
'packages' => $filled,
'cost' => $cost,
);
}
/* Test it! */
print_r(
fill_packages(
array(
array(
'name' => '18er',
'contain' => 18,
'cost' => 5
),
array(
'name' => '12er',
'contain' => 12,
'cost' => 5
),
array(
'name' => '6er',
'contain' => 6,
'cost' => 8
),
)
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment