【发布时间】:2016-06-03 00:20:45
【问题描述】:
我希望修改电子商务平台的折扣显示方式(OpenCart - 基于 PHP MVC)。
默认行为是折扣将显示为:
- 5 个或更多:$20.00
- 10 个或更多:18.00 美元
- 20 个或更多:$16.00
我更喜欢:
- 5 - 9:20.00 美元
- 10 - 19:18.00 美元
- 20 岁以上:16.00 美元
通过模板文件剥离“或更多”文本很简单(下面提供的代码)。
对于除最后一个元素之外的所有元素,这将需要从下一个元素中获取数量键 ($discount['quantity']) 并应用基本数学函数 (- 1),然后返回除原始值之外的新值。
对于最后一个元素,我只需要返回最后一个数量值并添加“+”文本。
原始代码(控制器):
$discounts = $this->model_catalog_product->getProductDiscounts($this->request->get['product_id']);
$this->data['discounts'] = array();
foreach ($discounts as $discount) {
$this->data['discounts'][] = array(
'quantity' => $discount['quantity'],
'price' => $this->currency->format($this->tax->calculate($discount['price'], $product_info['tax_class_id'], $this->config->get('config_tax')))
);
}
原始代码(模板):
<?php if ($discounts) { ?>
<div class="discount">
<?php foreach ($discounts as $discount) { ?>
<span><?php echo sprintf($text_discount, $discount['quantity'], $discount['price']); ?></span>
<?php } ?>
</div>
<?php } ?>
修改代码以从模板中删除“或更多”文本(注意:单独的 echo 用于允许表格格式 - 为了保持简单,不包括这些标签):
<?php if ($discounts) { ?>
<div class="discount">
<?php foreach ($discounts as $discount) { ?>
<?php echo $discount['quantity']; ?><?php echo $discount['price']; ?>
<?php } ?>
</div>
<?php } ?>
如何进一步修改此代码以返回首选格式的数量?
注意:阵列非常小,但我仍会优先考虑性能。
编辑:
感谢 tttony 提供以下解决方案。这是我在模板文件中用于自定义表格格式的代码(没有 sprintf/格式化字符串函数)。
<?php for ($i=0; $i < count($discounts) -1; $i++) { ?>
<tr>
<td><?php echo $discounts[$i]['quantity']; ?> - <?php echo (int)$discounts[$i+1]['quantity'] - 1; ?></td>
<td><?php echo $discounts[$i]['price']; ?></td>
</tr>
<?php } ?>
<?php if (count($discounts)) { ?>
<tr>
<td><?php echo $discounts[$i]['quantity']; ?>+</td>
<td><?php echo $discounts[$i]['price']; ?></td>
</tr>
<?php } ?>
【问题讨论】:
-
PHP 有
next、current、prev、last数组函数