【问题标题】:PHP multiple conditions for if statement in string字符串中if语句的PHP多个条件
【发布时间】:2016-03-27 05:36:05
【问题描述】:

我正在处理一封电子邮件,一旦我的数据库中的帐户访问/状态发生更改,该电子邮件将被发送出去。但是,我似乎无法让下面这个简单的 IF 语句起作用。我通过在 AND 和 && 之间切换来玩弄语法,但在这里找不到问题。

$email_message = "
<h1>User Account Update</h1><hr>
User <b>".$_SESSION['myusername']."</b> has just made changes to the following user account:<br>
<br>
Date: ".date("Y-m-d H:i:s", strtotime('+13 hours'))." (UTC+8)<br>
User: ".$user."<br>
<b>Action: ".str_replace("_"," ",$action)."</b><br>
<br>
Updated Access: ".if($action == "change_access" AND $access == "User") { echo "Admin"; } else { echo "User"; }."<br>
Updated Status: ".if($action == "change_status" AND $status == "Active") { echo "Inactive"; } else { echo "Active"; }."<br>
<hr>
If you suspect suspicious activity, you can suspend the account by following the link below:
";

if语句出现在字符串中时有什么特殊语法吗?

Updated Access: ".if($action == "change_access" AND $access == "User") { echo "Admin"; } else { echo "User"; }."<br>
Updated Status: ".if($action == "change_status" AND $status == "Active") { echo "Inactive"; } else { echo "Active"; }."<br>

编辑: 关于逻辑: 每当特权用户(管理员帐户)更改另一个用户的帐户状态或访问权限时,都会触发电子邮件警报。 用户 ACCESS 为“Admin”或“User”,用户 STATUS 为“Active”或“Inactive”。该消息告诉我受影响的帐户以及这两个变量的先前和当前状态。

【问题讨论】:

  • 你能解释一下你的情况背后的逻辑吗?比如“Admin”和“Inactive”是什么情况?
  • 你的代码在这么长的块里很难跟上……
  • 请参阅 Adam Azad 的回答,以获得更好的方法。将您的逻辑决策与构建电子邮件正文分开,否则将很难看到您的代码发生了什么。

标签: php if-statement


【解决方案1】:

使用三元确定变量值

$userType = (($action == "change_access" && $access == "User") ? "Admin" : "User");
$newStatus = (($action == "change_status" && $status == "Active") ? "Inactive" : "Active");

然后,将$email_message 中的内容打印出来

$email_message = "
<h1>User Account Update</h1><hr>
User <b>".$_SESSION['myusername']."</b> has just made changes to the following user account:<br>
<br>
Date: ".date("Y-m-d H:i:s", strtotime('+13 hours'))." (UTC+8)<br>
User: ".$user."<br>
<b>Action: ".str_replace("_"," ",$action)."</b><br>
<br>
Updated Access: ".$userType."<br>
Updated Status: ".$newStatus."<br>
<hr>
If you suspect suspicious activity, you can suspend the account by following the link below:";

【讨论】:

  • 完美运行,谢谢。尽管如此,我还是喜欢 Tim 的内联方法,这样我就不用定义更多的变量了。
  • @Armitage2k,您删除变量并将(($action == "change_access" &amp;&amp; $access == "User") ? "Admin" : "User") 移动到变量内部。 :)
【解决方案2】:

您还使用块 if 内联语句,并将结果回显到输出而不是将它们添加到变量中。

如果你必须内联你的 if 语句,试试

"Access: ".($action == "change_access" && $access == "User") ? "Admin" : "User"."<br> ...

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2013-12-17
    • 2011-08-27
    相关资源
    最近更新 更多