One more thing has popped up. It related to quantity. I've made some changes to the code. Basically if I have 2 of item 1 and 1 of item 2 my total weight needs to be 8. I need to multiply combinable items units by their quantity and then add the units all together. My total weight for package 1 should be 8, but no matter what I do the total weight is 6. Here is the code:
<?php
// this just recreates the supplied data
$items = array(
'1' => array(
'units' => 2,
'length' => 4,
'width' => 4,
'height' => 4,
'qty' => 2
),
'2' => array(
'units' => 4,
'length' => 6,
'width' => 6,
'height' => 6,
'qty' => 1
),
'3' => array(
'units' => 24,
'length' => 67,
'width' => 22,
'height' => 11,
'qty' => 1
),
);
$packages = array();
$max_girth = 60;
foreach ($items as $id => $i) {
$girth = 2 * $i['length'] + 2 * $i['width'] + $i['height'];
foreach($packages as &$p) {
if (($p['girth'] + $girth) <= $max_girth) {
$p['girth'] += $girth;
$p['weight'] += $i['units'] * $i['qty'] ;
$p['items'][$id] = $i;
continue(2); // this skips ahead to the next item
}
}
$packages[] = array(
'girth' => $girth,
'items' => array($id => $i),
'weight' => $i['units']
);
}
unset($p); // best not to leave references hanging around
echo "<pre>\n";
var_export($packages);
echo "</pre>\n";
foreach ($packages as $count => $package) {
echo 'Package ' . ($count+1) . ":\n";
echo "\ttotal weight: " . $package['weight'] . "\n";
echo "\tgirth: " . $package['girth'] ."\n";
echo "\tnumber of items: " . count($package['items']) ."<br><br>\n";
}
?>
And the output:
array (
0 =>
array (
'girth' => 50,
'items' =>
array (
1 =>
array (
'units' => 2,
'length' => 4,
'width' => 4,
'height' => 4,
'qty' => 2,
),
2 =>
array (
'units' => 4,
'length' => 6,
'width' => 6,
'height' => 6,
'qty' => 1,
),
),
'weight' => 6,
),
1 =>
array (
'girth' => 189,
'items' =>
array (
3 =>
array (
'units' => 24,
'length' => 67,
'width' => 22,
'height' => 11,
'qty' => 1,
),
),
'weight' => 24,
),
)
Package 1: total weight: 6 girth: 50 number of items: 2
Package 2: total weight: 24 girth: 189 number of items: 1