此函数使用单个折扣代码成功计算了全局百分比,尽管我在使代码折扣特定范围的项目而不是全局时遇到问题。购物篮会话包含 id、name、desc、price、qty 等...但是到目前为止我尝试过的一切都失败了,我意识到我需要将它实现到 foreach 循环中(我不断打破或更新每个项目的方式或其他)或完全使用不同的方法,但我真的不确定如何进行。
我不是一个经验丰富的 PHP 开发人员,我只是喜欢学习和使用基本标记。有人可以提供任何有用的指示将不胜感激。谢谢!
$code = $this->request['code'];
$discount_status = 'NONE'; // no discount available / applied
if ( !empty($this->config['DISCOUNT_CODE']) && !empty($this->config['DISCOUNT_PERCENT']) && !empty($code) ) {
if ( $code == $this->config['DISCOUNT_CODE'] ) {
$discount_status = 'OK';
}
else {
$discount_status = 'ERROR';
}
}
// calculate basket total
$basket_value = 0;
$discount_factor = 1;
if ( $discount_status == 'OK' ) {
// apply discount
$discount_factor = ( 100 - $this->config['DISCOUNT_PERCENT'] ) / 100;
}
if ( !empty($_SESSION['basket']) && is_array($_SESSION['basket']) ) {
foreach( $_SESSION['basket'] as $basketItem ) {
// Apply discount to each item separately
$basket_value += sprintf("%.02f", $basketItem['detail_price'] * $discount_factor) * $basketItem['qty'];
}
}
// check delivery cost
$delivery_area = $this->DeliveryAreaManager->getRecord($this->request['da']);
if ( !empty($delivery_area['cost']) && ( $delivery_area['free_from'] <= 0 || $basket_value < $delivery_area['free_from'] ) ) {
$basket_value += $delivery_area['cost'];
}
// return JSON response
$data = JSONUtils::encode(
array(
'discount_status' => $discount_status,
'basket_value' => sprintf("%.02f", $basket_value),
)
);
return $data;