dpt1712
2017-05-23 10:00
浏览 142
已采纳

检查多维数组中的所有数组是否满足特定条件

I want to perform a specific action if all arrays in a multidimensional array meet a specific condition when two of their values are subtracted.

What loop could help me achieve this type of result as shown in my code below:

$array = Array( 
    [0] => Array("id" => 1, "value1" => 7, "value2" => 10), 
    [1] => Array("id" => 2, "value1" => 6, "value2" => 10), 
    [2] => Array("id" => 3, "value1" => 8, "value2" => 11), 
    [3] => Array("id" => 4, "value1" => 9, "value2" => 12),
    [n] => Array( ...)
);

$val1 = $array[0]['value2'] - $array[0]['value1']; // 10 - 7 = 3
$val2 = $array[1]['value2'] - $array[1]['value1']; // 10 - 6 = 4
$val3 = $array[2]['value2'] - $array[2]['value1']; // 11 - 8 = 3
$val4 = $array[3]['value2'] - $array[3]['value1']; // 12 - 9 = 3
$valn = $array[n]...

if ($val1 < 5 && $val2 < 5 && $val3 < 5 && $val4 < 5 ... && valn < 5){

  //from my example, the answer is TRUE for all
 // Do this action

}else{
 // Do something else

}

图片转代码服务由CSDN问答提供 功能建议

如果多维数组中的所有数组的两个值都满足特定条件,我想执行特定操作 减去。

什么循环可以帮助我实现这种类型的结果,如下面的代码所示:

  $ array = Array(\  n [0] =&gt;数组(“id”=&gt; 1,“value1”=&gt; 7,“value2”=&gt; 10),
 [1] =&gt;数组(“id”=&gt;  2,“value1”=&gt; 6,“value2”=&gt; 10),
 [2] =&gt;数组(“id”=&gt; 3,“value1”=&gt; 8,“value2”=&gt;  ; 11),
 [3] =&gt;数组(“id”=&gt; 4,“value1”=&gt; 9,“value2”=&gt; 12),
 [n] =&gt;数组(。  ..)
); 
 
 $ val1 = $ array [0] ['value2']  -  $ array [0] ['value1'];  // 10  -  7 = 3 
 $ val2 = $ array [1] ['value2']  -  $ array [1] ['value1'];  // 10  -  6 = 4 
 $ val3 = $ array [2] ['value2']  -  $ array [2] ['value1'];  // 11  -  8 = 3 
 $ val4 = $ array [3] ['value2']  -  $ array [3] ['value1'];  // 12  -  9 = 3 
 $ valn = $ array [n] ... 
 
if($ val1&lt; 5&amp;&amp; $ val2&lt; 5&amp;&amp; $ val3&lt; 5&amp;  &amp; $ val4&lt; 5 ...&amp;&amp; valn&lt; 5){
 
 //来自我的例子,所有答案都为TRUE 
 //执行此操作
 
} else {  
 //做其他事情
 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqe9657 2017-05-23 10:05
    已采纳
    $all_less_than_5 = true;
    foreach($array as $item){
        if($item['value2'] - $item['value1'] >= 5){
             $all_less_than_5 = false;
             break;
        } 
    }
    if($all_less_than_5){
        // Do this action
    }else{
        // Do something else
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题