如何解决我将如何从此php循环中提取正确的值
| 我有这个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
)
)
解决方法
您可以将相关总数切换到数组:
$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)。但这给了你这个主意。
,我想这就是你想要的:
$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
结帐。
,我认为这是您想要的,但您的问题确实不清楚。
$arr = array(2,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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。