我有这个PHP循环
$two_related_total = 0;
$three_related_total = 0;
$four_related_total = 0;
$five_related_total = 0;
$all_values = getRelatedProducts(91)
$arr = array(2, 3, 4, 5);
foreach ($arr as $discount_quantity) {
//do something in here here to get the discounted_price or the price
}
以下是$ getRelatedProducts中的数据。基本上我需要获得每个阵列的折扣总额
例如,对于值2,我需要将$ two_related_total的值设置为729.0000等等......或者如果有更好的方法来获取这四个值,请帮助我....谢谢预先
[0] => Array
(
[product_id] => 180
[price] => 749.0000
[discounted_price] => 729.0000
[cost] => 420.0000
[quantity] => 2
)
[1] => Array
(
[product_id] => 180
[price] => 749.0000
[discounted_price] => 545.0000
[cost] => 420.0000
[quantity] => 3
)
[2] => Array
(
[product_id] => 180
[price] => 749.0000
[discounted_price] => 545.0000
[cost] => 420.0000
[quantity] => 4
)
[3] => Array
(
[product_id] => 180
[price] => 749.0000
[discounted_price] => 545.0000
[cost] => 420.0000
[quantity] => 5
)
)
答案 0 :(得分:1)
您可以将相关的总计切换为数组:
$related_totals=array();
$all_values = getRelatedProducts(91)
$arr = array(2, 3, 4, 5);
foreach ($arr as $discount_quantity) {
$related_totals[$discount_quantity]=$all_values[$discount_quantity]['price'];
//do something in here here to get the discounted_price or the price
}
我并不是真的理解你的问题,正如其他人指出的那样,没有729的价值,(虽然有749)。但是这给了你这个想法。
答案 1 :(得分:1)
我认为这就是你想要的:
$discounts = array();
foreach($product_array as $key => $product) {
$discounts[$key] = $product['discounted_price'];
}
echo $discounts[2]; // $545.00
使用数组来保存折扣比尝试为每个变量设置单个变量要容易得多。否则,随着产品阵列的增长,你最终会得到$five_hundred_bajillion_60_kajillion_and_3_discounted_total
。
答案 2 :(得分:1)
我认为这是你想要的,但你的问题真的不清楚。
$arr = array(2, 3, 4, 5);
$totals = array(2=>0, 3=>0, 4=>0, 5=>0);
foreach ( $all_values as $product ){
if (in_array($product['quantity'], $arr)) {
$totals[$products['quantity']] += $product['discounted_price'];
}
}
对于前两行,您也可以这样做:
$arr = range(2,5);
$totals = array_fill_keys($arr, 0);