我有一个像这样的数组对象
"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
如有任何帮助,我们将不胜感激,并提前致谢
这是您可以用来获取灵感的另一种方法。详情请见评论。
<?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'];
这里存储了您的计算数组,其中存储了数量及其总价格。由于您存储了带有货币符号的价格,因此在计算之前您需要删除该字符。
$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 );