Skip to content
Advertisement

Dividing up items based on quantity

We have a custom dispatch system where we have orders, if the total quantity within the order exceeds 2 then we need to split the contents over two orders. So for instance…

Order contains:

  • Item A x2
  • Item B x2

I need to move Item B to a second order.

Another example would be:

  • Item A x4

I would need to move 2 items to a second order so I’m left with Item A x2 in one output and the same in another output.

I’m using the following to loop through the items and quantities within an order.

$total_products = array();
foreach($products as $product){

  $product_id = $product['sellable']['id'];
  $product_quantity = $product['quantity'];
  $product_price = $product['price_per_unit'];

  array_push($total_products, array($product_id, $product_quantity, $product_price));
}

How can I total up the items in that order – as soon as any of the quantities hit 2, can I move those to a second array? Is using multiple arrays the best approach for this?

This is an example of an array that’s been generated (this can be variable):

Array
(
    [0] => Array
        (
            [0] => 39235995
            [1] => 3
            [2] => 2.81
        )

    [1] => Array
        (
            [0] => 39236029
            [1] => 1
            [2] => 2.952
        )

    [2] => Array
        (
            [0] => 39236015
            [1] => 1
            [2] => 3.333
        )

    [3] => Array
        (
            [0] => 39235997
            [1] => 1
            [2] => 2.667
        )

)

Advertisement

Answer

Managed to figure this out by using the following, this gives me the separate parcels I needed:

// Add the product info we need into a new array
$total_products = array();
foreach($products as $product){

  $product_id = $product['sellable']['id'];
  $product_quantity = $product['quantity'];
  $product_price = $product['price_per_unit'];

  $total_products[] = array('id' => $product_id, 'quantity' => $product_quantity, 'price' => $product_price);
}

// Separate out the quantities for each product, one per array
$resultArr = [];
foreach($total_products as $item){
  for($i = 0; $i < $item['quantity']; $i++){
      $resultArr[] = array(
        'id' => $item['id'],
        'quantity' => 1,
        'price' => $item['price'],
      );
  }
}

// Divide up into the correct amount of parcels
$parcel_size = 2;
$parcels = array_chunk($resultArr, $parcel_size);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement