【问题标题】:Run PHP code with certain conditions enabled or disabled在启用或禁用某些条件的情况下运行 PHP 代码
【发布时间】:2016-06-18 02:21:05
【问题描述】:

我已经在这里问过这个问题。 Run php code conditionally

我对数据库做了一些修改。 之前给出的答案可能是正确的,我已经尝试过但不起作用。 这些答案可能超出了我对 PHP 的理解。

以下是同一问题的改写版本。

我要替换的实际代码

if ($condition1 >= $offer1 AND $condition2 >= $offer2  AND 
$condition3 >= $offer3  AND  $condition4 >= $offer4     ) 
      {  //run code }
else {  //some error messages  }

$condition1 and all are numeric value 
$offer1  and all are numeric value

我想用新代码替换此代码。示例如下。

if ($offercurrent[0]>=$offerpoints[0] AND $offercurrent[1]>=$offerpoints[1]  AND 
$offercurrent[2]>=$offerpoints[2] AND  $offercurrent[3]>=$offerpoints[3]     ) 
      {  //run code }
else {  //some error messages  }

$offerstatus = enabled or disabled
$offercurrent = numeric values
$offerpoints = numeric values


$offercurrent   $offerpoints  status
 50               51           enabled
100               99           enabled
122               865          disable
NNN               offern       disable

数据库值

      while($row = mysql_fetch_array($sql))  
{
$offername[] = $row['name'];
$offercurrent[] = $row['current'];
$offerstatus[] = $row['status'];
$offerpoints[] = $row['points'];

}

问题:

只有在 offerstatus= enabled 时才应该运行代码。一个这个条件是满足的。它应该检查所有出现的offercurrent和offerpoints。
我试图用这个替换以前的代码

    $check=false;
    for ($i=0;$i<count($offerstatus);$i++) { 
           //echo "$offerstatus[$i]";
            if ($offerstatus[$i]=="enabled")  { 
           if($offercurrent[$i]>=$offerpoints[$i]) {$check=true;}
            echo "$offername[$i]";}
                                          } 

    echo "$check";

if ($check=true) { //run code } 
else {//error messages}

使用此代码检查总是返回 1 (true) 它只检查第一个值并忽略其余值。

【问题讨论】:

  • 你在 if 中为 $check 赋值为 true
  • if($offercurrent[$i]>=$offerpoints[$i]) 。如果这是真的,那么检查将是真的。
  • if ($check=true) 必须是 if ($check === true) if ($check == true) 使用单个 = 为变量赋值而不是检查它。

标签: php mysql sql arrays for-loop


【解决方案1】:

通过在代码中添加else解决了这个问题。

$check=false;
for ($i=0;$i<=count($offerstatus);$i++) { 
       //echo "$offerstatus[$i]";
        if ($offerstatus[$i]=="enabled")  { 
       if($offercurrent[$i]>=$offerpoints[$i]) {$check=true;}
                       else{  $check=false;   
        break; //if $condition is less than $offer it will get out of loop.
                                   }
        }
                                      } 

if ($check=true) { //run code } 
else {//error messages}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2017-10-09
    • 2020-12-07
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多