如果foreach中的条件知道所有匹配

时间:2018-03-24 14:46:18

标签: php if-statement foreach

我有这个$fields数组:

Array
(
    [0] => Array
        (
            [field] => Name
            [condition] => 0
            [value] => abc
        )

    [1] => Array
        (
            [input] => Username
            [condition] => 1
            [value] => xyz
        )

    [2] => Array
        (
            [input] => Email
            [condition] => 1
            [value] => xyz@gmail.com
        )
    ...
)

条件0等于且条件1不等于。我怎么能注意到所有的比赛。

如果只有所有条件匹配,我需要回应一些事情。我的意思是if value is abc for name and value is not xyz for username and value is not xyz@gmail.com for email field.

foreach( $fields as $field ) {
   if( $field['condition'] == 0 ) {
       if( $field['value'] == 'value_from_input') {
           echo 'something';       
       }
    }
    elseif( $field['condition'] == 0 ) {
      if( $field['value'] == 'value_from_input') {
           echo 'something';       
       }
   } 
}

然而,这似乎是OR条件,如果有任何匹配,则存在回声。我需要所有条件来匹配。

此致

1 个答案:

答案 0 :(得分:1)

将标志设置为true,然后遍历数组,当存在不匹配的编码时,将标志设置为false并跳出循环。如果循环后标志仍为真,则可以确保所有条件匹配:

$fields = [
    [
        "field" => "Name",
        "condition" => 0,
        "value" => "abc",
    ],
    [
        "field" => "Username",
        "condition" => 1,
        "value" => "abc",
    ],
    [
        "field" => "Email",
        "condition" => 1,
        "value" => "abc",
    ],
];
$success = true;
foreach( $fields as $field ) {
   if ($field["condition"] === 0) {
       $success = false;
       break;
   }
}
if ($success) { 
    echo "All conditions match";
}
else {
    echo "Some conditions don't match";
}

Demo

实际上有很多方法可以做到这一点。另一个是过滤条件不匹配的字段,然后比较每个数组的count

$filtered = array_filter($fields, function($el) {
    return $el["condition"] === 0;
});
$success = count($fields) === count($filtered);
if ($success) { 
    echo "All conditions match";
}
else {
    echo "Some conditions don't match";
}