-1

我想建立一个if then包含/不包括最终标准的标准的声明。

例子 :

$vanilla_on=true;
$sugar_on=false;
$flour_on=true;

$vanilla=10;
$sugar=2;
$flour=100;

// As I set $vanilla_on to false, it doesn't appear in my if statement, if it was set to true, it would be added && ($vanilla < 100)
if ( ($sugar>2) && ($flour>90) )
{
  // ok
}

基本上,如果相应的布尔值设置为 true,我只想检查香草、糖和面粉的情况。因此,如果我有 vanilla_on=false,则包含多少单位的香草并不重要,因为我们只会检查糖和面粉的状况。

4

3 回答 3

1
$vanilla_ok = true;
if ($vanilla_on === true && $vanilla < 5) {
    $vanilla_ok = false;
}

if (... && $vanilla_ok)
{
    // ok
}
于 2013-11-14T10:26:20.167 回答
1
// these are "switches" that will tell the if statement which components to check
$vanilla_on=true;
$sugar_on=false;
$flour_on=true;

// components
$vanilla=10;
$sugar=2;
$flour=100;

// only check that the component meets the thresholds *if* it's "on"
if ( ($sugar>2 || !$sugar_on) && ($flour>90 || !$flour_on) && ($vanilla < 100 || !$vanilla_on) )
{
  // ok
  echo "OKAY!";
}

它的工作方式是这样的:您有一个 if 语句,它必须评估为 TRUE 才能使事情“正常”。假设您需要检查所有三个组件以确保它们都在阈值内,那么所有 3 个条件都必须为真,才能使整个语句评估为真。如果 AND 中只有一个条件为假,那么整个事情都是假的。

但是,假设您不在乎使用了多少香草。只要糖和面粉的测量值在阈值范围内,您使用多少香草就与确定情况是否正常无关。为此,您将每个单独的组件包装在括号中,并将其与相应的“on”布尔值进行或。

简而言之,如果 $vanilla_on 为假,这意味着您不在乎使用了多少香草,您可以取布尔值的相反值,真,然后将其与阈值比较进行 OR。由于 (true OR false) 始终计算为 true,因此无论您使用多少 vanilla,if 语句的该部分始终返回 true。同样,如果 $sugar_on 为真,则相反的值为假,因此为了使 if 语句的那部分为真,我们现在仅依靠糖阈值落在通过小于比较确定的范围内。

简而言之,将问题分解为单个组件,然后将它们全部组合在一起。

于 2013-11-15T06:50:52.997 回答
0

好的,我找到了一种简单的方法。

if (a)
{
if (b) {c=true} else {c=false}
}
else
{
c=true
}

repeat for all _on variables

if (c) && (d) ...
于 2013-11-15T14:45:16.027 回答