当我使用php操作数计算百分比时,我得到以下Fatal error: Unsupported operand types
,这是我使用的代码
<p>
<?php
$baseprice = get_field_object('base_price');
$basediscount = get_field_object('discount_applied');
?>
Total price:
<?php
$division = $baseprice / $basediscount;
$res = round($division * 100);
echo $res;
?>
</p>
这是我下面的代码的链接
您似乎忘记了使用括号来指定round
函数中的参数。你可能是指
$res = round($division * 100);
而不是
$res = round$division * 100;
(这会让PHP认为您试图使用$
作为操作数,而不是通常的+
、-
、/
、*
、&
、%
、|
等。(
我已经更改了您的代码并简化了它。我检查了
<?php
$baseprice = 120.00;
$basediscount = 10; //assuming it's 10%
$discount = round($baseprice*$basediscount/100);
$price_after_discount = $baseprice-$discount;
//the other option to count price after discount with 1 line
/*$price_after_discount = $baseprice-round($baseprice*$basediscount/100);*/
echo "discount: $discount<br />";
echo "price after discount $price_after_discount";
?>
有了这个代码,没有错误,它很好地计算了折扣。上面代码的结果是折扣108后的折扣12
注意:
你不检查$basediscount
变量,如果它是0,那么它将是致命的错误,因为你不能除以0
请更正您的代码:-
$res = round($division * 100);
请参阅工作方式手册:http://php.net/manual/en/function.round.php
检查$baseprice
和$basediscount
数据类型。我不确定它是整数还是浮点。
我已经为您生成了一个案例,如果$baseprice
或basediscount
数组,那么您将收到此错误。参见此处
http://codepad.org/BjxgN2lY
如果它是int或float,那么它肯定会为您工作:-如下面的演示所示。
http://codepad.org/JC9QxMio
$res = round($division * 100);
执行此操作之前,请检查if($division > 0 )
ie(
if($division > 0 )
{
$res = round($division * 100);
echo $res;
}