基本布尔逻辑——如何仅在另一个条件为真时才测试条件
我知道这是基本的布尔逻辑,但我被卡住了:
我正在循环访问数据库结果,对于每个结果,我需要检查以下条件:
if($old_value != $new_value)
如果上述为真,则操作为:
$old_value = $new_value;
但还有一个次要条件。如果该行的类型为“date”,我还需要检查 $new_value 是否不为空,但操作仍然相同。现在,我正在这样做:
if($old_value != $new_value) {
if($type != date) {
$old_value = $new_value;
} elseif(!empty($new_value)) {
$old_value = $new_value;
}
我对上面的内容进行了过度简化,但实际上这一行操作实际上是几行,我知道我不需要根据次要条件重复这些行。
但我不知道如何将内在条件与外在条件结合起来。如果我做类似的事情:
if(($old_value != $new_value) && ($type == 'date' && !empty($new_value))
那么它唯一返回 true 的时候是当该行的类型为日期时。
I know this is basic boolean logic, but I'm stuck:
I am looping through database results, and for each one I need to check for the following condition:
if($old_value != $new_value)
If the above is true, the action is:
$old_value = $new_value;
But there is a secondary condition. If the row is of type "date", I need to also check that $new_value
is not empty, but the action is still the same. Right now, I am doing it like this:
if($old_value != $new_value) {
if($type != date) {
$old_value = $new_value;
} elseif(!empty($new_value)) {
$old_value = $new_value;
}
I've oversimplified the above, but really that one-line action is actually several lines that I know I don't need to repeat based on the secondary condition.
But I'm at a loss on what the right way to combine the inner condition with the outer condition. If I do something like:
if(($old_value != $new_value) && ($type == 'date' && !empty($new_value))
Then the only time it would return true is when the row is of type date.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
应该可以。如果您需要帮助了解原因,请告诉我。
Try:
That should do it. Let me know if you need help understanding why.
if(($old_value != $new_value) && ($type != 'date' || ($type == 'date' && !empty($new_value)))
也许这个可以缩短,但我想不出怎么做。
if(($old_value != $new_value) && ($type != 'date' || ($type == 'date' && !empty($new_value)))
Maybe this one can be made shorter but I can't think of how.