php - 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
任何帮助将不胜感激,并提前感谢
解决方案
这里存储了数量及其总价的计算数组。由于您存储了带有货币符号的价格,因此在计算之前您需要删除该字符。
$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 );
推荐阅读
- node.js - 从 Express 中间件在整个节点应用程序中共享令牌
- java - Spring Data Elasticsearch 4.2.x:DateFormat 抛出空指针
- javascript - 如何使用 d3-contour 绘制简单的 2D 等高线图?
- wcag - 为了确保 WCAG 1.4.11“非文本对比度”的通过对比度,我是否将 :hover 的“颜色”属性与非悬停颜色或背景进行比较?
- r - 在拆分元素之前合并
- javascript - [[scope]] 键内的块是什么以及它是何时创建的?
- scikit-learn - 更改 OneclassSVM 中预测函数的输出类标签值
- dynamic - 在数据库中存储页脚部分
- flutter - 在 BLoC 中打开数据库表,在 MyApp 中处理 - 这有效吗?
- video-streaming - 在 Dash.JS 中处理视频的代码部分是什么?