首页 > 解决方案 > PHP的价格中断数量

问题描述

我有一个这样的数组对象

"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"
  }
],

我想根据上面的json之类的数量来计算价格。我的预期输出是这样的

+ 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

任何帮助将不胜感激,并提前感谢

标签: phparraysjsonprice

解决方案


这里存储了数量及其总价的计算数组。由于您存储了带有货币符号的价格,因此在计算之前您需要删除该字符。

$json = '{
    "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"
    }]
}';
  $data = json_decode( $json, true );
  $calculation = [];
  foreach ($data['PriceBreaks'] as $value) {
      $calculation [] = [
          'quantity' => $value['Quantity'],
          'total_price' => $value['Quantity'] * str_replace('$','', $value['Price'])
      ];
  }
  var_dump( $calculation );

推荐阅读