Search code examples
phparraysjson

Price break quantity for PHP


I have a array object like this

"PriceBreaks": [
  {
    "Quantity": 1,
    "Price": "$12.10",
    "Currency": "USD"
  },
  {
    "Quantity": 5,
    "Price": "$11.76",
    "Currency": "USD"
  },
  {
   "Quantity": 10,
   "Price": "$11.42",
   "Currency": "USD"
  },
  {
    "Quantity": 25,
    "Price": "$10.75",
    "Currency": "USD"
  }
],

I want to calculate the price based on quantity like json above. My expected output like this

+ Quantity is 1 => price is $ 12.10
+ Quantity is 4 => price is 4 * $ 12.10
+ Quantity is 5 => price is 5 * $ 11.76
+ Quantity is 8 => price is 8 * $ 11.76

Any Help would be appreciated and thanks in Advance


Solution

  • Here is another approach you may use for inspiration. See the comments for details.

    <?php
    
    // Raw JSON
    $json = '[
      {
        "Quantity": 1,
        "Price": "$12.10",
        "Currency": "USD"
      },
      {
        "Quantity": 5,
        "Price": "$11.76",
        "Currency": "USD"
      },
      {
       "Quantity": 10,
       "Price": "$11.42",
       "Currency": "USD"
      },
      {
        "Quantity": 25,
        "Price": "$10.75",
        "Currency": "USD"
      }
    ]';
    
    // Convert JSON to array using the quantity as the index.
    $offers = [];
    // TRUE to convert to associative array.
    foreach (json_decode($json, TRUE) as $offer)
    {
        // Let's get a float for the calculations instead of the string.
        $offer['Price'] = +substr($offer['Price'], 1);
        // Store as quantity => offer.
        $offers[$offer['Quantity']] = $offer;
    }
    
    // The number of items to be purchased.
    $customerQuantity = 10;
    
    // max(1, ...) will ensure that the key will never go below 1.
    // floor($customerQuantity / 5) * 5 to get to the nearest boundary. This assumes that quantities are always a multiple of 5!
    echo $offers[max(1, floor($customerQuantity / 5) * 5)]['Price'] * $customerQuantity;