3v4l.org

run code in 300+ PHP versions simultaneously
<?php $products = array ( 0 => array ( 'product_id' => 2, 'customer_id' => 1820, 'order_id' => 'M-AAH-959', 'quantity' => 5, 'weight' => 1.3, 'cubic' => 0.00267, 'total_weight' => 6.5, 'total_cubic' => 0.00267 ), 1 => array ( 'product_id' => 3, 'customer_id' => 1820, 'order_id' => 'M-AAH-959', 'quantity' => 6, 'weight' => 1.5, 'cubic' => 0.00348, 'total_weight' => 9, 'total_cubic' => 0.00348 ), 2 => array ( 'product_id' => 8, 'customer_id' => 1820, 'order_id' => 'M-AAH-959', 'quantity' => 7, 'weight' => 1.5, 'cubic' => 0.00267, 'total_weight' => 10.5, 'total_cubic' => 0.00267 ) ); function pack_boxes($products, $box_weight) { $boxes = array(); $this_box_weight = 0; $box_number = 0; foreach ($products as $product) { // will all this product fit? if ($product['total_weight'] < $box_weight - $this_box_weight) { // yes - add this product to the box $boxes[$box_number][] = $product; $this_box_weight += $product['total_weight']; $boxes[$box_number]['box_weight'] = $this_box_weight; } else { // no - add the part that will fit to this box $num_products = floor(($box_weight - $this_box_weight) / $product['weight']); $balance = $product['quantity'] - $num_products; $product['quantity'] = $num_products; $product['total_weight'] = $num_products * $product['weight']; $boxes[$box_number][] = $product; $boxes[$box_number]['box_weight'] = $this_box_weight + $num_products * $product['weight']; // add the balance to a new box $box_number++; $product['quantity'] = $balance; $this_box_weight = $product['total_weight'] = $balance * $product['weight']; $boxes[$box_number][] = $product; $boxes[$box_number]['box_weight'] = $this_box_weight; } } return $boxes; } $boxes = pack_boxes($products, 12); print_r(array_column($boxes, 'box_weight')); print_r($boxes);

preferences:
24.55 ms | 406 KiB | 5 Q