dpt1712
2017-05-23 10:00 阅读 65
已采纳

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

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

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dqe9657 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
    }
    
    点赞 评论 复制链接分享

相关推荐