有条件地运行php代码

时间:2016-03-03 15:51:50

标签: php mysql sql arrays

我想在基础上运行代码或从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

示例输出和数组值

while($row = mysql_fetch_array($sql))  
{
$offerstatus[] = $row['offer_status'];
//some more output
}
  

存储在此数组中的值$ offerstatus [] =启用或禁用

这些值存储参考提供
示例值

offer   status 
offer1  enabled
offer2  enabled 
offer3  disable
offern  disable

condition     offer status
 50           51    enabled
100           99    enabled
122          865    disable
NNN          offern disable

我想基于从此数组 $ offerstatus [] 返回的值运行上述查询.so只有匹配其值已启用的条件。
问题:
我想为所有已重新启用的值运行此代码,并希望匹配这些条件。

基于样本值

以上内容应自动转为

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

如果问题没有得到澄清,请告诉我。

3 个答案:

答案 0 :(得分:2)

条件和报价必须在数组中

$condition=array(50,100,122);
$offer=array(51,99,865);

现在过滤那些值已启用

的数组
function filter_enabled($val){
    if($val=='enabled'){
        return true;
    }
}

$filtered_offerstatus=array_filter($offerstatus,'filter_enabled');

现在$filtered_offerstatus仅包含启用的值,现在检查条件是否大于等于

$check=false;
foreach($filtered_offerstatus as $key=>$value){

        if($condition[$key]>=$offer[$key]){
            $check=true;
        }
        else{
            $check=false;
            break; //if $condition is less than $offer it will get out of loop.
        }
}

现在,如果所有值都设置为 true ,则代码将被执行,否则错误消息

if($check===true){
    echo "Execute Code";
}
else{
    echo "Some Error Message";
}
  

注意:我们假设$ condition,$ offer和$ offerstatus具有相同的数组长度,否则该程序将无效。

答案 1 :(得分:1)

您将不想使用>=运算符。将其换成===。您的$ condition变量也需要是字符串值enable / disable。然后您的评估IF集团将与此类似:

if ('enabled' === 'enabled'  AND 'disabled' !== 'enabled') {
    //run code
} else {
    //some error messages 
}

答案 2 :(得分:0)

你可以试试这个:

/* SAMPLE VALUE */
$offerstatus = array('1'=>'enabled','2'=>'enabled','3'=>'disable');//in your case from your bdd

$condition1 = 15;
$offer1 =10;
$condition2 = 15;
$offer2 =10;


$one_condition_error=false;//boolean to check if all condition is true

foreach($offerstatus as $offer => $status){//foreach offerstatus
    if($status=='enabled'){//only if this offerstatus is enabled
        if(${'condition'.$offer} < ${'offer'.$offer}){// i check if conditionN < offerN : ${'test_'.$i}  -> $test1 if $i =1
            $one_condition_error=true;//one error detected
        }

    }       
}

if($one_condition_error){
    echo 'at least one offerstatus error';
}else{
    echo 'all offerstatus ok';

}
相关问题