I have a data that looks like this

"discountPrices": [
    {
      "startQuantity": 3,
      "price": 65.0
    },
    {
      "startQuantity": 8,
      "price": 62.0
    },

   {
      "startQuantity": 20,
      "price": 60.0
    },

  ]

As you know, this is a discount price of a product. I am trying to achieve two things here.

1.) I want to create a table called discountprice and the table will have columns namely price | minqty | maxqty. Using the data above, the first row will be 65.00 | 3 | 7 , and the second row will be 62.00 | 8 | 19 and the third row will be 60 | 20 | 1000. The issue I am first here is that I don't know how to get the maximum qty because the data did not contain the maximum quantity. It only states the startQuantity. How can I get the Maxquanity for each of the row and record it?

2.) How can I output it on a page. For example, using the data, I can do something like 3>=7 = $65.00, 8>=19 = $62.00 , 20>=1000 = $60.00

I think the hardest part is how to know the maximum quantity since it is not specified. Please how can I achieve this result.

2 Answers

0
Rakesh Kumar Jakhar On Best Solutions

You can use the following code snnipt to get the max quantity

$json = '[  
 {  
  "startQuantity":3,
  "price":65.0
 },
 {  
  "startQuantity":8,
  "price":62.0
 },
 {  
  "startQuantity":20,
  "price":60.0
 }
]';

$jsonToArray = json_decode($json, true);
$startQuantity = array_column($jsonToArray, 'startQuantity');
array_walk($jsonToArray, function($v, $k) use (&$jsonToArray, $startQuantity) {
    $index = array_search($v['startQuantity'], $startQuantity);
    if(array_key_exists($index+1, $startQuantity))
         $jsonToArray[$k]['endQuantity']  = $startQuantity[$index+1]-1;
});
print_r($jsonToArray);

Result

Array
(
[0] => Array
    (
        [startQuantity] => 3
        [price] => 65
        [endQuantity] => 7
    )

[1] => Array
    (
        [startQuantity] => 8
        [price] => 62
        [endQuantity] => 19
    )

[2] => Array
    (
        [startQuantity] => 20
        [price] => 60
    )

)
1
Alex Howansky On

You don't need to know the max qty. Just store your data as is and query for the first row that has a startQuantity less than or equal to your orderQuantity:

SELECT price FROM discounts
    WHERE startQuantity <= :orderQuantity
    ORDER BY startQuantity DESC
    LIMIT 1

See here for example.

If you don't find a result, then there's no discount and your price is just the base undiscounted price. (Or you could insert a row with the base price and 0 for startQuantity.)

Note, I assume you're selling more than one product, so you'll likely need a field in that table (and the associated WHERE clause) to identify which product.