我在处理一个简单的php代码时遇到了问题。
我使用两个产品定价层。这些基于用户是否已登录。
如果用户未登录,并且第一个价格为空;那么价格就是price1。如果不是,则为price1.
这非常好用。
如果用户已登录,并且第一个价格为空;那么价格就是price1。如果不是,那就是价格2。
这是它应该工作的方式,但实际发生的是:
如果用户已登录,并且第一个价格为空;则价格为0。如果不是,那就是价格2。
为什么我的代码会产生这种效果?
if (!userIsLoggedIn())
{
if (empty($prPrice2))
{
$prPrice = $prPrice1;
}
else
{
$prPrice = $prPrice1;
}
} else if (userIsLoggedIn())
{
if (empty($prPrice2))
{
$prPrice = $prPrice1;
}
else
{
$prPrice = $prPrice2;
}
} else
{
$prPrice = $prPrice1;
}
如果有人有任何建议可以帮助我解决这个问题,我们将不胜感激。
谢谢!
@佩卡,这相当复杂。我只是希望这种情况发生:
product 1 -> price 1 = 1.00
product 1 -> price 2 = 0.00
product 2 -> price 1 = 1.00
product 2 -> price 2 = 0.80
如果用户已登录,但price2字段为空,则价格变量将为price1。如果没有,那么价格是2。
另一方面,如果用户未登录,但price2字段为空,则价格变量将为price1。如果没有,那么它将是价格1。
您解释规则的方式有点令人困惑。您应该能够修改以下代码以适应:
if (userIsLoggedIn()) {
$prPrice = !empty($prPrice2) ? $prPrice2 : $prPrice1;
} else {
$prPrice = !empty($prPrice1) ? $prPrice1 : $prPrice2;
}
代码与您描述的算法相矛盾。
你告诉过:
如果用户未登录并且第一个价格为空,则价格就是价格。如果不是,那就是价格2。如果用户已登录并且第一个价格为空,然后价格为price1。如果不是,那就是价格2。
因此,事实上,无论用户是否登录,算法都应该做完全相同的事情。
在你的代码中,它也很奇怪:
你有三个条件:
- 用户未登录
- 用户已登录
- 其他
用户已登录或未登录。我看不到任何其他可能性。
还有,下面几行:
if (empty($prPrice2))
{
$prPrice = $prPrice1;
}
else
{
$prPrice = $prPrice1;
}
可以降低为
$prPrice = $prPrice1;
因为您在两个代码块中执行相同的操作。
您的代码过于复杂,并且包含一些奇怪的构造。这是一个等效但简化的版本,但请查看我在第一个上添加的注释。。。。
if (!userIsLoggedIn())
{
if (empty($prPrice2))
{
$prPrice = $prPrice1;
}
else
{
$prPrice = $prPrice1; // this is highly suspicious...
}
} else { // user is logged or not, no need to recheck that boolean var
if (empty($prPrice2))
{
$prPrice = $prPrice1;
}
else
{
$prPrice = $prPrice2;
}
}
用三元语句表达相同条件的一种稍微花哨的方式(示例等效于外部if的else块:
$prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice2;
编辑
假设有一种方法可以区分未登录的帐户持有人和没有帐户的用户,您需要在外部条件下处理,如以下所示:
if ($UserHasAnAccount) {
// but i don't understand (yet) how you'd know that at this point
if (userIsLoggedIn()) { // the price logic described before
....
} else {
....
}
} else { // unknown user, price1
$prPrice = $prPrice1;
}
else
{
$prPrice = $prPrice1;
}
您无法达到这个条件,因为据我所知,userIsLoggedIn
是布尔型的,它可能只在两个条件下发生:当userIsLoggedIn为true时和当它为false时。你写的
如果用户未登录并且第一个价格为空,则价格为price1。如果不是,那就是价格2。
但在你的代码中会发生这种情况:
如果用户未登录并且第二个价格为空,则价格为price1。如果不是,则也是价格1。
同样在条件userIsLoggedIn you write that
如果用户登录并且第一个价格为空
但在代码中,您要检查第二个价格是否为空。