首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当变量显示数值等于0时,如何应用if条件?

当变量显示数值等于0时,如何应用if条件?
EN

Stack Overflow用户
提问于 2022-07-24 18:02:40
回答 1查看 41关注 0票数 -1

我是计算购买的产品的折扣,根据其原价和折扣价格。数学运算成功了,我得到了正确的结果。

目前,当没有折扣0.00是显示,所以我想显示自定义文本,而不是值0,最终结果可能是“没有折扣应用”或类似的东西。

为了做到这一点,我考虑了是否和其他条件,但我不知道如何正确地应用它们,我是相对较新的。下面我留下我的代码解释一些事情,我希望有人帮助我和澄清这一点,我感谢任何答复,谢谢。

变量:我正在使用woocommerce,但我认为这是不相关的,因为php是关键的部分。无论如何,我有两个变量来恢复产品的原始价格和折扣价格:

代码语言:javascript
运行
复制
$regular_price = $product->get_regular_price(); //Get original price
$total_discounted = $item->get_total(); //Get discounted price

计算:下面是考虑到这两个变量的计算折扣的php代码行。如果没有折扣,则显示值0,当应用折扣时,将显示正确的结果。请注意,我计算了折扣和百分比的总和。

代码语言:javascript
运行
复制
<?php echo ' <span class="item-value summary">'. number_format( ($regular_price - $total_discounted),2 ) .'€ ('. number_format( (($regular_price - $total_discounted) / $regular_price*100),1 ) .'%)</span> '; ?>

下面,我留下了在这两个变量上执行var_dump所看到的内容。在现实中,xx是表示产品原价的数字,它从不为零。

代码语言:javascript
运行
复制
<?php 
var_dump($regular_price); 
string(2) "xx" //Content - xx indicates the original price of the product

var_dump($total_discounted); 
string(2) "xx" //Content - xx indicates the original price of the product
?>

我的疑问是,如果这两个变量都没有返回0,我该如何应用?计算结果显然返回0,但变量不返回。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-29 12:51:25

这是解决问题的办法。我创建了其他变量来定义如下的if条件:

代码语言:javascript
运行
复制
$discount_sum  = number_format( ($regular_price - $total_discounted),2 );
$discount_percentage = number_format( (($regular_price - $total_discounted) / $regular_price*100),1 ); 
  if ($discount_sum == 0 and $discount_percentage == 0) { 
  echo '<span class="item-label summary t2-light">Nessuno sconto applicato</span>';
} else {
  echo '<span class="item-value summary highlight">'. wp_kses_post($discount_sum) .'€ ('. wp_kses_post($discount_percentage) .'%)</span>';
                }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73100856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档